我有一张桌子documents
和一张桌子labels
。我是名为doc_labels
的多对多关联的第三个表。
构建我的SQL语句以选择与label1
和label2
我尝试了以下内容:
SELECT * FROM documents d RIGHT JOIN doc_labels dl
ON(d.id = dl.doc_id)
WHERE dl.label_id = 1 AND dl.label_id = 2
此声明不会返回任何内容。
SELECT * FROM documents d RIGHT JOIN doc_labels dl
ON(d.id = dl.doc_id)
WHERE dl.label_id = 1 OR dl.label_id = 2
此声明将返回带有label1
OR label2
如何选择label1
和label2
的所有文档。
感谢您的帮助。
答案 0 :(得分:2)
你可以这样做
SELECT * FROM documents d
RIGHT JOIN doc_labels dl
ON(d.id = dl.doc_id)
WHERE dl.label_id IN(1,2)
GROUP BY d.id
HAVING COUNT(DISTINCT dl.label_id) >= 2 /*this will give you the documents that must have lable 1,2 and can have more lables*/
或者,如果您需要仅包含标签1和2的文档,请更改
HAVING COUNT(DISTINCT dl.label_id) = 2