当两个表上不存在匹配的记录时,SQL连接3个表

时间:2017-01-12 10:45:07

标签: mysql join left-join

我有3张桌子 - domains, keywords, comments

domains是“主”表,所有这些表都有公共字段domain_id。我需要编写一个查询,如果它们在其他(domainskeywords)表中没有匹配的记录,则从comments表中选择记录。

我编写一个选择匹配记录的查询没有问题,但是如何实现相反的呢?看How to do LEFT JOIN with more than 2 tables?我写了一个查询:

SELECT * FROM domains 
LEFT JOIN keywords ON domains.domain_id=keywords.domain_id WHERE keywords.domain_id IS NULL 
LEFT JOIN comments ON domains.domain_id=comments.domain_id WHERE comments.domain_id IS NULL

部分工作。它选择keywords表中没有匹配项的记录,但忽略comments表。所以,根据我发现的其他话题,写了这个:

SELECT * FROM 
(domains LEFT JOIN keywords ON domains.domain_id=keywords.domain_id WHERE keywords.domain_id IS NULL) 
LEFT JOIN comments ON domains.domain_id=comments.domain_id WHERE comments.domain_id IS NULL

这个根本不起作用(语法错误)。如何修改查询以完成工作?我猜第一个查询应该差不多......

1 个答案:

答案 0 :(得分:3)

在所有加入之后放置where子句,如下所示

如果您要选择domainskeywords两个表中不存在的comments,请在OR子句中使用WHERE条件

SELECT * FROM domains 
LEFT JOIN keywords ON domains.domain_id=keywords.domain_id 
LEFT JOIN comments ON domains.domain_id=comments.domain_id 
WHERE keywords.domain_id IS NULL 
OR comments.domain_id IS NULL

如果要选择domainskeywords两个表中不存在的comments,只需替换OR子句中的WHERE条件到下面的AND

SELECT * FROM domains 
LEFT JOIN keywords ON domains.domain_id=keywords.domain_id 
LEFT JOIN comments ON domains.domain_id=comments.domain_id 
WHERE keywords.domain_id IS NULL 
AND comments.domain_id IS NULL