0

有两个表:

content_term
    cid | tid
    1 | 1
    1 | 2
    1 | 3
    2 | 4
    2 | 5
    2 | 6

term_group
    tid | gid
    1 | 1
    2 | 2
    3 | 3
    4 | 1
    5 | 2
    6 | 3

如何通过“tid”选择未链接到某个“gid”的“cid”?

UPD 我已经尝试过 Adrian 的按 cid 分组的方式:

SELECT cid 
FROM   content_term ct 
WHERE  NOT EXISTS (SELECT tid 
               FROM   term_group tg 
               WHERE  tg.tid = ct.tid 
                      AND tg.gid = 4) GROUP BY cid;

并且还尝试了 Adrian 的按 cid 分组的方式:

SELECT cid FROM content_term
    LEFT JOIN term_group ON (content_term.tid = term_group.tid AND gid = 4)
    WHERE gid IS NULL GROUP BY cid;

在 "gid" = 3 或任何其他值上 - 他们都返回:

cid
1
2
4

2 回答 2

0
SELECT cid 
FROM   content_term ct 
WHERE  NOT EXISTS (SELECT tid 
                   FROM   term_group tg 
                   WHERE  tg.tid = ct.tid 
                          AND tg.gid = 4) 
于 2012-08-24T14:43:23.330 回答
0

这个:

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)
于 2012-08-24T14:51:34.050 回答