简体   繁体   English

Mysql:选择与左联接不能按预期方式

[英]Mysql: Select with Left Join not working as expected

I have a query of the following type: 我有以下类型的查询:

select * from tbl_1 where [cond] as aliasA LEFT JOIN tbl_2 as aliasB 
 ON (aliasA.id = aliasB.id) WHERE aliasB.id IS NULL

It appears that it's working except that it's ignoring the last WHERE aliasB.id IS NULL . 除了忽略最后一个WHERE aliasB.id IS NULL以外,它似乎在工作。 So, it's just returning the results of: 因此,它只是返回以下结果:

select * from tbl_1 where cond as aliasA LEFT JOIN tbl_2 as aliasB 
 ON (aliasA.id = aliasB.id)

How would I change the above query to get the results of querying tbl_1 where [cond] displaying only the rows that are not in tbl_2? 我如何更改上述查询以获得查询tbl_1的结果,其中[cond]仅显示不在tbl_2中的行?

Thanks in advance! 提前致谢!

aliasB.id = NULL will always be false. aliasB.id = NULL将始终为false。 The correct way is aliasB.id IS NULL or the uglier MySQL-specific aliasB.id <=> NULL 正确的方法是aliasB.id IS NULL或较丑的MySQL特定的aliasB.id <=> NULL

Orignal Ans at : How do I decide when to use right joins/left joins or inner joins Or how to determine which table is on which side? Orignal Ans at: 如何确定何时使用右连接/左连接或内部连接,或者如何确定哪张表在哪一边?

Best way i found is have look to below image clear out you doubt 我发现的最好方法是查看下面的图片以清除怀疑

Check the case 1 and 2 in image will give you your answer 检查图片中的情况1和2将为您提供答案

and change you where condition to WHERE aliasB.id is NULL 并将您的条件更改为WHERE aliasB.id is NULL

替代文字

You could try: 您可以尝试:

SELECT * FROM tbl_1 aliasA LEFT JOIN tbl_2 aliasB
ON aliasA.id = aliasB.id
WHERE condA 
  AND aliasB.id IS NULL

http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html http://dev.mysql.com/doc/refman/5.0/en/working-with-null.html

You need to use "IS NULL" instead of "= NULL" 您需要使用“ IS NULL”而不是“ = NULL”

您需要使用IS NULL来检查NULL值,而不是= NULL

WHERE aliasB.id IS NULL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM