我不太确定这叫做什么,但我花了一些时间思考它,我不知道如何处理它。我确定这很简单。
我有两张桌子,foo和bar。他们是这样的:
Foo表:
| id | name
--------------
| 1 | blah
| 2 | blarg
| 3 | blag
酒吧表(baz的含义无关紧要):
| fooId | baz |
---------------
| 1 | 100 |
| 1 | 94 |
| 1 | 27 |
| 2 | 94 |
| 3 | 19 |
所以,每个Foo多个Bars。我想选择所有他们的baz为94的Foos,除非他们的baz为100.所以在上面的例子中我只想选择id为2的Foo。
我尝试过按照以下方式做的事情:
SELECT id FROM foo
LEFT JOIN bar
ON foo.id = bar.fooId
WHERE bar.baz = 94
AND bar.baz != 100
但很明显,到目前为止只有我。我确定这里可能有某种group by子句,但我不确定它应该是什么。
提前致谢!
答案 0 :(得分:6)
select id from foo
inner join bar b1 on b1.fooId=foo.id and b1.baz=94
left outer join bar b2 on b2.fooId=foo.id and b2.baz=100
where b2.fooId is null
技术术语是"anti-join"。正常的内连接是“等连接”。
答案 1 :(得分:3)
SELECT id
FROM foo f
JOIN bar b1 ON f.id = b1.fooId
LEFT JOIN bar f2 ON f.id = b2.fooId AND b2.baz = 100
WHERE b1.baz = 94
AND b2.fooid is null
答案 2 :(得分:2)
SELECT id FROM foo
LEFT JOIN bar
ON foo.id = bar.fooId
WHERE bar.baz = 94
AND NOT EXISTS (
SELECT bar2.fooId FROM bar bar2
WHERE bar2.fooId = bar.foodI AND bar2.baz = 100)
我是怎么做的。
答案 3 :(得分:2)
您可以使用EXISTS和子查询获得所需的结果:
SELECT id
FROM foo
WHERE EXISTS (SELECT fooId FROM bar WHERE fooId = foo.id AND baz = 94)
AND NOT EXISTS (SELECT fooId FROM bar WHERE fooId = foo.id AND baz = 100)
答案 4 :(得分:0)
可能是这样的:
SELECT id FROM foo where存在(select * from bar,其中foo.id = bar.fooId和bar.baz = 94) 并且不存在(从bar中选择*,其中foo.id = bar.fooId和bar.baz = 100)