Consider this schema
CREATE TABLE [PrimaryTable]
[Id] int IDENTITY(1,1) NOT NULL
ALTER TABLE [PrimaryTable]
ADD CONSTRAINT [PK_PrimaryTable]
PRIMARY KEY ([Id])
CREATE TABLE [SecondaryTable]
[PrimaryTableId] int NOT NULL
[Name] nvarchar(4000) NOT NULL
[Value] nvarchar(4000) NULL
ALTER TABLE [SecondaryTable]
ADD CONSTRAINT [PK_SecondaryTable]
PRIMARY KEY ([PrimaryTableId],[Name])
And then the following data
PrimaryTable
| Id |
| 1 |
| 2 |
| 3 |
SecondaryTable
| PrimaryTableId | Name | Value |
| 1 | xxx | yyy |
| 2 | xxx | zzz |
I am attempting to write a query which will give me all the entries in PrimaryTable
that DO NOT have a name/value of xxx=yyy
, including those where there is no entry in SecondaryTable
for xxx
Currently I have the following which only returns ID = 2, and not ID = 3
SELECT Id FROM PrimaryTable
LEFT OUTER JOIN SecondaryTable ON PrimaryTable.Id = SecondaryTable.PrimaryTableId
WHERE (SecondaryTable.Name = 'xxx' AND SecondaryTable.Value NOT LIKE 'yyy')
Describing the additional clause in plain English would be something along the lines of ...OR SecondaryTable.Name = 'xxx' does not exist
Edit
I should note that I've simplified both the table structure and the query for this question - other columns from PrimaryTable
will also be retrieved (as well as form part of the query), and there are additional queries on SecondaryTable
using different name/value combinations, and different operators (=, !=, LIKE, NOT LIKE)
(Environment is SQL Server LocalDb 2014)