选择具有相同ID但在其他列中不同的值

时间:2015-09-04 10:57:08

标签: sql ms-access-2013

我已经拿到了这张桌子。

拥有:

Pid Cid
100 1
100 2
200 1
200 3
300 4
400 1
400 4
400 5
500 2
500 4

我只需要选择Cid = 1而不是Cid = 2的Pid 输出应该是:

pid
200
400

我的查询是:

SELECT Pid
FROM OWNS 
WHERE Cid = 1 and Cid <> 2

但我得到了结果:

pid
100
200
400

2 个答案:

答案 0 :(得分:1)

尝试

SELECT distinct Pid 
FROM OWNS 
WHERE 
   Pid not in (select Pid from OWNS where Cid = 2) 
AND CID = 1;

答案 1 :(得分:0)

或者这个:

SELECT `pid` 
FROM `OWNS` 
WHERE `cid` = '1' 
    AND `pid` in (SELECT `pid` 
                  FROM `OWNS` 
                  WHERE `cid` != '1' AND `cid` != '2')