所以我正在研究一个SQL问题,我有一个酒吧和啤酒数据库,我想从中: 列出所有供应迈克喜欢的啤酒的酒吧,以及不止一个饮酒者经常光顾的啤酒。
数据库包括:
likes (drinker, beer)
frequents(dinker, bar)
sells(bar, beer)
所以我试过了:
SELECT bar
FROM beer.sells
WHERE beer IN
(SELECT beer
FROM beer.likes
WHERE drinker = 'Mike') AND bar IN
(SELECT bar FROM beer.frequents HAVING COUNT(drinker) > 1)
哪个不起作用...为什么计数(饮酒者)比较不能作为过滤器过滤出频繁出现频率少于2个饮酒者的酒吧?
答案 0 :(得分:2)
在条形子查询中看起来需要GROUP BY bar
。否则,您将从COUNT(*)
有效地获得beer.frequents
,这不是您想要的:
SELECT bar
FROM beer.sells
WHERE beer IN
(SELECT beer
FROM beer.likes
WHERE drinker = 'Mike') AND bar IN
(SELECT bar FROM beer.frequents GROUP BY bar HAVING COUNT(drinker) >= 2)
答案 1 :(得分:2)
您需要'GROUP BY'才能使聚合的COUNT有效:
SELECT bar
FROM beer.sells
WHERE beer IN
(SELECT beer
FROM beer.likes
WHERE drinker = 'Mike'
)
AND bar IN
(SELECT bar
FROM beer.frequents
GROUP BY bar
HAVING COUNT(drinker) > 1
)
答案 2 :(得分:1)
“经常出现超过一个饮酒者。”<> HAVING COUNT(drinker) > 2
( 1 )
SELECT bar
FROM beer.sells
WHERE beer IN
(SELECT beer
FROM beer.likes
WHERE drinker = 'Mike')
AND bar IN
(SELECT bar
FROM beer.frequents
GROUP BY bar
HAVING COUNT(drinker) > 1)