Please see the DDL below:
CREATE TABLE TestTable(id int, [name] varchar(30))
CREATE TABLE TestTable2(id int, [name] varchar(30))
INSERT INTO TestTable (id,[name]) values (1,'')
INSERT INTO TestTable (id,[name]) values (2,'Martin')
INSERT INTO TestTable2 (id,[name]) values (1,null)
INSERT INTO TestTable2 (id,[name]) values (2,'Martin')
select TestTable.* from TestTable
LEFT JOIN TestTable2
ON TestTable.id=TestTable2.id
and TestTable.[name]= TestTable2.[Name] and NOT (TestTable.[name] ='' and TestTable2.[name] is null)
where testtable2.id is null
The SELECT returns one row and I would expect it to return none. The reason I would expect it to return none is the same reason the SQL statement below returns none:
select TestTable.* from TestTable
LEFT JOIN TestTable2
ON TestTable.id=TestTable2.id
and TestTable.[name]= TestTable2.[Name]
where testtable2.id is null and NOT (TestTable.[name] ='' and TestTable2.[name] is null)
Why does the first SQL statement return one row? The ON clause should filer out those records with this criteria: NOT (TestTable.[name] ='' and TestTable2.[name] is null). The one row returned contains this criteria. Why?
A LEFT JOIN
will return all rows from the left table unless they are filtered out by the WHERE
criteria, your first query WHERE
criteria excludes 1 row, the WHERE
in your second query excludes both rows.
Update: A popular reference for understanding Joins is:
Visual Representation of SQL Joins
ON
is used to define how the tables will be joined together, WHERE
to limit the results. In the case of an INNER JOIN
they both limit results, with an OUTER JOIN
the difference between them becomes appreciable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.