我有一个链接表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(在此示例中为1
和3
)?我是否必须求助于子查询?
答案 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')