我有3张桌子 - domains, keywords, comments
表domains
是“主”表,所有这些表都有公共字段domain_id
。我需要编写一个查询,如果它们在其他(domains
和keywords
)表中没有匹配的记录,则从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
这个根本不起作用(语法错误)。如何修改查询以完成工作?我猜第一个查询应该差不多......
答案 0 :(得分:3)
在所有加入之后放置where
子句,如下所示
如果您要选择domains
和keywords
两个表中不存在的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
如果要选择domains
和keywords
两个表中不存在的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