SQL 使用 where 子句离开 JOIN 不返回所有结果

yus*_*sof 0 postgresql left-join

我有 2 个使用 ID 加入的表。如果该 ID 在表 #2 中,我希望主表中的所有数据都显示并匹配,以在我的输出中显示更多列。目前与

select table1.id, table1.name, table1.phone, table1.address, 
table2.loyalcustomer, table2.loyaltynumb, table2.loyaltysince from table1
left join table2
ON table1.id = table2.table1id
Run Code Online (Sandbox Code Playgroud)

我想做的是同样的事情,但在 table2.loyalcustomer != 'Yes' 中添加一个 WHERE 子句。当我这样做时,它不会返回我的主表(table1)中的所有数据,而是只显示 table1 和 table2 之间的匹配项。此外,table2 没有所有信息,只有插入表中的信息。

select table1.id, table1.name, table1.phone, table1.address, 
table2.loyalcustomer, table2.loyaltynumb, table2.loyaltysince from table1 
left join table2
ON table1.id = table2.table1id
WHERE table2.loyalcustomer != 'Yes'
Run Code Online (Sandbox Code Playgroud)

一直在阅读不同的连接,但我一直在阅读的是我的 where 语句可能与我的连接相矛盾,我不知道如何解决这个问题。

SQL 数据库:Postgres

Dav*_*vid 5

问题出在您的 WHERE 子句上。小心左连接!

当您对 TABLE 执行 LEFT JOIN 时,该表不会像 INNER JOIN 一样过滤结果。这是因为您接受 LEFT JOIN TABLE 以返回整个 NULL 行。

但是,当您说... "table2.loyalcustomer != 'Yes'" 时,您在 WHERE 子句中使用了来自“LEFT JOINED TABLE”的 COLUMN 。此子句在 table2.loyalcustomer 不为空时有效,但如果 table2.loyalcustomer 为 NULL 则无效。

所以这里是正确的方法:

select table1.id, ... from table1 left join table2 ON table1.id = table2.table1id and table2.loyalcustomer != 'Yes'

这里有另一种方法来做到这一点......

select table1.id, ... from table1 left join table2 ON table1.id = table2.table1id WHERE ISNULL(table2.loyalcustomer, '') != 'Yes'

继续: NULL != 'Yes' 不起作用。您需要与 null 不同的东西来评估您的表达式。