ID | NAME | REFERENCE | STATUS
-------------------------------
1 | name1 | 123 | 0
2 | name1 | 123 | 1
3 | name2 | 111 | 0
4 | name3 | 222 | 0
5 | name5 | 555 | 1
我们说我有这个表TABLE1。我需要一个select语句,它只能找到STATUS = 0的记录,但是如果"相同"记录存在STATUS = 1(如ID为1和2的记录)
因此,查询必须只找到第三和第四条记录。
答案 0 :(得分:0)
尝试此查询:
SELECT A.*
FROM TABLE1 A
LEFT JOIN TABLE1 B ON
A.ID = B.ID AND
A.NAME = B.NAME AND
A.REFERENCE = B.REFERENCE AND
B.STATUS = 1
WHERE A.STATUS = 0
AND B.REFERENCE IS NULL
WHERE子句中对B.REFERENCE的NULL检查基本上确保在LEFT JOIN中找不到匹配的记录(你也可以只使用B.ID或B.NAME)。
答案 1 :(得分:0)
根据您的建议结果,我将您的问题读作“仅查找状态为0的记录,其中相同的名称/参考组合没有状态= 1的记录”。
一种方法是使用not exists
子句:
select t.*
from table t
where status = 0 and
not exists (select 1
from table t2
where t2.name = t.name and
t2.reference = t.reference and
t2.status = 1
);
答案 2 :(得分:0)
MINUS
可用于获取Status为0但不为1的值。
SELECT ID, Name, Reference, Status
FROM Table1
WHERE (Name, Reference) IN (SELECT Name, Reference
FROM Table1
WHERE Status = 0
MINUS
SELECT Name, Reference
FROM Table1
WHERE Status = 1)
答案 3 :(得分:0)
SELECT * FROM TABLE WHERE NAME NOT IN
(
SELECT NAME FROM
TABLE
GROUP BY NAME
HAVING COUNT(DISTINCT STATUS)>1
) AND STATUS='0';