困境:此查询实现了“找到喜欢Caravan出售的至少一种啤酒的所有饮用者”
“IN”关键字就像一个大规模的OR语句。
目标查询是:找到喜欢Caravan提供的每种啤酒的饮用者
SELECT drinker
FROM BarBeerDrinker.likes
WHERE BarBeerDrinker.likes.beer IN (
SELECT beer
FROM BarBeerDrinker.sells
WHERE BarBeerDrinker.sells.bar = "Caravan"
);
架构:
喜欢表格
drinker beer
John "Blue Moon"
Mike "Blue Moon"
John “Budweiser”
Mike “Budweiser”
John "Creamy Dark"
Mike "Creamy Dark"
Mike “Hefeweizen”
John “Killian's”
John "Michelob Golden Draft"
Mike "Michelob Golden Draft Light"
John "Original Premium"
Mike "Original Premium Lager"
Jesse "Original Premium Lager Dog"
Mike "Original Premium Lager Dog"
John "Stolichnaya Citrona"
卖表
bar beer
"A.P. Stump's" Hefeweizen
"Blue Angel" "Hefeweizen Doppelbock"
"Blue Angel" "Original Premium Lager Dog"
"Blue Tattoo" Killian's
"Britannia Arms" Budweiser
Cabana Budweiser
Caravan Budweiser
Caravan "Original Premium Lager Dog"
.
.
.
预期输出 麦克
答案 0 :(得分:0)
我希望这可能有用,如果没有,请不要投票(如果我拼错了) (别名可能需要AS关键字,取决于数据库类型)
select count(*), drinker from (
select a.drinker, b.beer
FROM BarBeerDrinker.likes a , BarBeerDrinker.likes b
where a.beer = b.beer and b.bar = 'Caravan'
group by a.drinker, b.beer )
group by drinker
having count(*) = ( select count(*) from BarBeerDrinker.likes c where c.bar = 'Caravan' )
答案 1 :(得分:0)
首先要知道NOT(喜欢)=(喜欢X喜欢) - 喜欢
这将给我'notlikes'表,其中记录了不喜欢特定啤酒的饮酒者。
notlikes = select a.drinker, b.beer
from Likes a join Likes b
MINUS
select l.drinker, l.beer
from Likes l
现在获取不喜欢Caravan所供应/出售的所有饮料的饮用者名单
notanswer = select notlikes.drinker
from notlikes, Sells
where notlikes.beer = Sells.beer and Sells.bar = 'Caravan'
获取在Caravan喝啤酒的饮用者的完整清单
drinkers = select l.drinker
from Likes l join Sells s
where l.beer = s.beer and s.bar = 'Caravan';
要获得答案,请从饮酒者中减去消息
answer = drinkers - notanswer;
答案 2 :(得分:0)
我会走另一条路:
在第一天,我在大篷车(caravanbeer)搜索所有啤酒,然后我只加入那些喜欢的大篷车 - 但我只对那些我无法加入的人感兴趣 - 他们是NULL。然后我带走所有不在这个结果中的人:
Project MESSAGE: Fetching production code
Project MESSAGE: Production code fetched!
Project MESSAGE: Headers: path\to\production\mainwindow.h
Project MESSAGE: Sources: main.cpp path\to\production\main.cpp path\to\production\mainwindow.cpp
Project MESSAGE: Forms: path\to\production\mainwindow.ui
答案 3 :(得分:0)
http://sqlfiddle.com/#!9/a066b/2
我在向示例提供的数据示例中做了一些更改,查询在不同的数据值组合中工作,所以在我的情况下,查询根据我的数据返回Jessy
和Mike
。
SELECT l.drinker, s.s_count
FROM sells
LEFT JOIN (
SELECT bar,
COUNT(DISTINCT beer) s_count
FROM sells
GROUP BY bar
) s
on sells.bar = s.bar
LEFT JOIN likes l
ON l.beer = sells.beer
WHERE s.bar = "Caravan"
GROUP BY drinker
HAVING COUNT(DISTINCT l.beer) = s.s_count