我有一个链接表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
但没有的 id spam
(在这个例子中:1
和3
)?我必须求助于子查询吗?
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
Select id From table1
Where prop = 'ham' and id not in (select id from table1 where prop = 'spam')