如何为此编写sql查询:

时间:2012-11-16 06:43:29

标签: mysql sql tsql

mysql> select * from table3 order by id;
+------+-------+
| id   | value |
+------+-------+
|    1 | a     |
|    1 | b     |
|    1 | c     |
|    1 | d     |
|    2 | a     |
|    2 | b     |
|    3 | a     |
|    3 | b     |
|    3 | c     |
|    4 | a     |
|    4 | b     |
+------+-------+

我想选择所有没有值'c'的ID。

它不会简单地通过以下查询工作:

mysql> select distinct id from table3 where value <> 'c';
+------+
| id   |
+------+
|    1 |
|    2 |
|    3 |
|    4 |
+------+

我只需要只返回2和4

感谢您的关注!

2 个答案:

答案 0 :(得分:2)

这对你有用

select distinct id from table3 where 
             id not in ( select id from table3 where value = 'c')

答案 1 :(得分:1)

select distinct id 
from table3 t
where not exists 
                 (select 1 from table3 where value = 'c' and id = t.id)