SQL语句翻译

时间:2013-02-26 12:50:09

标签: sql oracle

我是SQL的新手,这是我第一次尝试将这种语句翻译成SQL。

  

找到经常为所有酒吧提供啤酒的饮用者John Smith喜欢

我有以下三个表来回答它:

FREQUENTS(DRINKER, BAR) 
SERVES(BAR, BEER) 
LIKES(DRINKER, BEER)

这是我不成功的做法:

SELECT DISTINCT F1.DRINKER
FROM FREQUENTS F1
WHERE F1.DRINKER<>'John Smith'
AND   F1.DRINKER NOT IN(SELECT F2.DRINKER
                        FROM FREQUENTS F2
                    WHERE F2.BAR NOT IN (SELECT S.BAR 
                                        FROM SERVES S, LIKES L
                                        WHERE L.DRINKER='John Smith'
                                        AND S.BEER=L.BEER
                                        AND L.DRINKER=F2.DRINKER))

任何人都可以帮我弄清楚如何修复它吗?

2 个答案:

答案 0 :(得分:1)

尝试此查询

SELECT DISTINCT F1.DRINKER
FROM FREQUENTS F1 
WHERE F1.BAR IN (SELECT S.BAR FROM SERVES S, LIKES L
                                    WHERE L.DRINKER='John Smith'
                                    AND S.BEER=L.BEER)

我删除了您创建的额外子查询

答案 1 :(得分:0)

好的,我明白了。这不是很优雅,如果在执行此代码期间数据得到更新,那么这可能不起作用,但在这里它是

DECLARE @bars TABLE (bar nvarchar(max))
DECLARE @drinkers TABLE (drinker nvarchar(max))
DECLARE @drinkerCounts TABLE (count int, drinker nvarchar(max))
DECLARE @barCount int

insert into @bars
select distinct bar from serves where beer in
(select beer from likes where drinker = 'John Smith')

select @barCount = COUNT(*) from @bars

insert into @drinkers
select drinker from frequents f
inner join @bars b on f.bar = b.bar
where drinker <> 'John Smith'

insert into @drinkerCounts
select count(drinker), drinker
from @drinkers
group by drinker

select * from @drinkerCounts dc
where dc.Count = @barCount