鉴于这两个表:
Foo (id, name) -- PK = id
Bar (fooId, value) -- PK = composite, fooId + value
-- value is a non-negative int
如何找到0 {/ p>以上没有对应Foo.name
的所有Bar,value
?
例如:
Foo
id name
1 a
2 b
3 c
Bar
fooid value
1 0
1 1
2 0
3 4
Result:
b
答案 0 :(得分:2)
SELECT Name
FROM Bar
INNER JOIN Foo ON Foo.Id = Bar.fooId
GROUP BY fooId, name
HAVING SUM(Value) = 0
此查询和zodeus发布的查询大约需要相同的执行时间,但是这个查询不会包含任何未被Bar表引用的Foo记录。例如,如果你还有记录Foo(4,d),这个查询仍将返回'b',因为zodeus的查询将返回'b'和'd'。
答案 1 :(得分:1)
SELECT name FROM FOO WHERE id NOT IN(
SELECT fooId FROM Bar GROUP BY fooId HAVING MAX(Value) > 0)
答案 2 :(得分:1)
我发现以下内容最容易阅读和理解......
SELECT foo.name
FROM foo
WHERE NOT EXISTS (SELECT 'x'
FROM bar
WHERE bar.fooid = foo.id
AND bar.value > 0)
答案 3 :(得分:0)
select Foo.name
from Foo
where Foo.id not in
(select Bar.fooid from Bar
where value > 0)