这个:
SELECT DISTINCT cid FROM content_term
JOIN term_group ON (content_term.tid = term_group.tid AND gid = 4);
将所有 cid 映射到 gid 4。我们现在需要所有不在此列表中content_term
的cid。因此,我们在唯一 cid 和刚刚检索到的附加 cid 之间使用 a:LEFT JOIN
SELECT unique_cids.cid FROM ( SELECT DISTINCT cid FROM content_term ) AS unique_cids
LEFT JOIN ( SELECT DISTINCT cid FROM content_term
JOIN term_group ON (content_term.tid = term_group.tid AND gid = 4) )
AS attached_cids ON (unique_cids.cid = attached_cids.cid)
WHERE attached_cids.cid IS NULL;
测试:
CREATE TABLE content_term ( cid integer, tid integer );
CREATE TABLE term_group ( tid integer, gid integer );
INSERT INTO content_term VALUES (1,1),(1,2),(1,3),(2,4),(2,5),(2,6);
INSERT INTO term_group VALUES (1,1),(2,2),(3,3),(4,1),(5,2),(6,3);
首先尝试使用 gid 4:
SELECT unique_cids.cid FROM ( SELECT DISTINCT cid FROM content_term )
AS unique_cids
LEFT JOIN ( SELECT DISTINCT cid FROM content_term
JOIN term_group ON (content_term.tid = term_group.tid AND gid = 4))
AS attached_cids ON (unique_cids.cid = attached_cids.cid)
WHERE attached_cids.cid IS NULL;
+------+
| cid |
+------+
| 1 |
| 2 |
+------+
2 rows in set (0.00 sec)
使用 gid 3 重试:
SELECT unique_cids.cid FROM ( SELECT DISTINCT cid FROM content_term )
AS unique_cids
LEFT JOIN ( SELECT DISTINCT cid FROM content_term
JOIN term_group ON (content_term.tid = term_group.tid AND gid = 3))
AS attached_cids ON (unique_cids.cid = attached_cids.cid)
WHERE attached_cids.cid IS NULL;
Empty set (0.00 sec)