加入“不存在”的条件

时间:2013-11-04 21:30:45

标签: mysql sql

我有一个链接表object_id -> property

id  |  prop
----|-------
1   |  ham
1   |  baz
1   |  whatever

2   |  spam
2   |  ham
2   |  whatever

3   |  ham
3   |  quux

4   |  foo
4   |  spam

如何仅选择包含ham但不包含spam的ID(在此示例中为13)?我是否必须求助于子查询?

2 个答案:

答案 0 :(得分:2)

SELECT DISTINCT id
  FROM tbl o
 WHERE prop = 'ham'
   AND NOT EXISTS (SELECT null
                     FROM tbl i
                        WHERE o.id = i.id
                          AND i.prop = 'spam')

使用LEFT JOIN可以完成同样的操作,但是mysql查询优化器会为它生成类似的执行计划。所以这是一个选择的优先选择问题。

加成:

SELECT DISTINCT t1.id
  FROM tbl t1
  LEFT JOIN tbl t2 ON t1.id = t2.id
                  AND t2.prop = 'spam'
 WHERE t1.prop = 'ham'
   AND t2.id IS NULL

答案 1 :(得分:1)

Select id From table1 
Where prop = 'ham' and id not in (select id from table1 where prop = 'spam')