1

请考虑以下 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 |  
+----+--------+----------+  

我想选择结果 = ko 和引用 = 47 的行,因为引用 47 在结果 = ok 的任何行中都不存在。除此之外,我只想要这一行一次,因为这种情况发生了两次(id=6 和 id=9),尽管它可能发生一次。实际上,在我要查询的查询中,id=89 的行也应该出现,如 reference = 89、result = ko 并且没有其他行的 reference = 89 和 result = ok。非常感谢您!

4

2 回答 2

1

您可以使用不存在的子查询

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');

您也可以使用 self left join 来做到这一点:

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
于 2013-03-20T21:47:26.117 回答
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
于 2013-03-20T21:45:11.617 回答