SQL将JOIN与where子句不返回所有结果

时间:2018-06-14 15:53:18

标签: 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

我正在尝试做的是同样的事情,但是向table2.loyalcustomer添加一个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'

一直在阅读不同的联接,但我一直在阅读的是我的where声明可能与我的加入相矛盾,我不知道如何解决这个问题。

SQL DB:Postgres

2 个答案:

答案 0 :(得分:4)

问题在于WHERE子句。小心LEFT JOINS!

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

但是,你正在使用你的" LEFT JOINED TABLE"中的一个列。在你的WHERE子句中,当你说..." table2.loyalcustomer!='是'" 。当table2.loyalcustomer不为null但是如果table2.loyalcustomer为NULL则它有效。

所以这是正确的方法:

选择table1.id,... 来自table1 left join table2 ON table1.id = table2.table1id and table2.loyalcustomer!='是'

这是另一种方法......

选择table1.id,... 来自table1 left join table2 ON table1.id = table2.table1id 在哪里ISNULL(table2.loyalcustomer,'')!='是'

要恢复:NULL!='是'不起作用。你需要与null不同的东西来评估你的表达。

答案 1 :(得分:0)

试试这个男人

SELECT table1.id, table1.name, table1.phone, table1.address, 
table2.loyalcustomer, table2.loyaltynumb, table2.loyaltysince FROM users 
LEFT JOIN table2
ON table1.id = table2.table1id
HAVING table2.loyalcustomer != 'Yes'
相关问题