请考虑以下MySQL表
|----+--------+----------|
| id | result |reference |
|----+--------+----------|
| 1 |ok | 33 |
| 2 |ok | 46 |
| 3 |ko | 55 |
| 4 |ko | 55 |
| 5 |ok | 55 |
| 6 |ko | 47 |
| 7 |ko | 89 |
| 8 |ok | 91 |
| 9 |ko | 47 |
+----+--------+----------+
我想选择result = ko和reference = 47的行,因为引用47在result = ok的任何行中都不存在。除此之外我只需要这一行,因为这种情况会发生两次(id = 6和id = 9),尽管它可能会发生一次。实际上在我要求的查询中,id = 89的行也应该出现,作为reference = 89,result = ko,并且没有其他行带有reference = 89和result = ok。 非常感谢你提前!
答案 0 :(得分:1)
您可以使用subquery with not exists:
SELECT DISTINCT result, reference
FROM [dbo].[references] as x
WHERE NOT EXISTS
(SELECT * FROM [dbo].[references] as y
WHERE
y.reference = x.reference
and
y.result = 'ok');
您也可以使用自我左联接:
SELECT DISTINCT x.result, x.reference
FROM [dbo].[references] as x
LEFT JOIN
[dbo].[references] as y
on x.reference = y.reference
and y.result = 'ok'
WHERE
y.reference IS NULL
答案 1 :(得分:0)
使用条件,有效:
IF EXISTS (Select TOP 1 * from <thistable>
WHERE result='OK' AND reference=47)
SELECT Select TOP 1 * from <thistable>
WHERE result='OK' AND reference=47
ELSE
SELECT Select TOP 1 * from <thistable>
WHERE result='KO' AND reference=47
END