SQL选择以消除在下一列中具有2个其他值的重复值

时间:2013-12-31 07:29:10

标签: mysql sql select group-by junction-table

我构建了一个像这样的联结表。

表名: myTable

p_id | c_id
-----------
1     1
1     2
1     3
2     2    
2     3
3     2
3     3
3     4

我想SELECT p_id,它没有c_id 3和4.在这种情况下,只有p_id 3同时具有c_id 3和4所以在select语句之后,查询应该同时返回p_id 1和2。 问题是我尝试了不同的方法,但它仍然不起作用。我真的需要帮助。

我的查询

1。)SELECT DISTINCT p_id FROM myTable WHERE c_id != 3 AND course_id != 4;

问题:它仍然返回3作为结果之一,因为3的c_id为2

5 个答案:

答案 0 :(得分:2)

这样的事情:

SELECT DISTINCT p_id 
FROM   mytable 
WHERE  p_id NOT IN (SELECT p_id 
                    FROM   mytable 
                    WHERE  c_id IN ( 3, 4 ) 
                    GROUP  BY p_id 
                    HAVING Count(DISTINCT c_id) = 2)

SQLFiddle demo

答案 1 :(得分:0)

试试这个:

SELECT DISTINCT p_id 
FROM myTable 
WHERE c_id IN (3,4) 
GROUP BY p_id HAVING COUNT(DISTINCT c_id)<2

答案 2 :(得分:0)

直接的解决方案是使用 exists

  select 
distinct p_Id
    from myTable t
   where not (exists (select 1
                        from myTable
                       where (c_id = 3) and
                             (p_id = t.p_id)) and 
              exists (select 1
                        from myTable
                       where (c_id = 4) and
                             (p_id = t.p_id)))

答案 3 :(得分:0)

试试这个:

SELECT mytable.p_id 
FROM   mytable 
       LEFT OUTER JOIN (SELECT v1.p_id 
                        FROM   (SELECT p_id 
                                FROM   mytable 
                                WHERE  c_id = 3) v1 
                                INNER JOIN (SELECT p_id 
                                            FROM   mytable 
                                           WHERE  c_id = 4) v2 
                                       ON v1.p_id = v2.p_id) v 
                    ON mytable.p_id = v.p_id 
WHERE  v.p_id IS NULL 
GROUP  BY mytable.p_id 

答案 4 :(得分:0)

试试这个:

select distinct mytable.p_id from mytable where c_id not in (3,4) and p_id <>3

这将给出没有3和4的结果