选择没有特定字段的其他记录的行

时间:2016-03-07 18:52:28

标签: mysql

Ciao大家,我有下表:

ID - COL_A - COL_B

我需要检索COL_A = 1的所有记录,而COL_A = 1的COL_B必须没有COL_A = 2的其他记录。

你能帮帮我吗?

由于

1 个答案:

答案 0 :(得分:1)

我认为这是NOT EXISTS的案例:

SELECT *
FROM mytable AS t1
WHERE COL_A = 1 AND 
      NOT EXISTS (SELECT 1
                  FROM mytable
                  WHERE t1.COL_B = t2.COL_B AND COL_A = 2)  

您还可以使用LEFT JOIN

SELECT t1.*
FROM mytable AS t1
LEFT JOIN mytable AS t2 ON t1.COL_B = t2.COL_B AND t2.COL_A = 2
WHERE t1.COL_A = 1 AND t2.COL_A IS NULL