2010-05-03 53 views
2

查詢查找「以相同價格銷售三種不同啤酒的所有酒吧?」查詢查找以相同價格銷售三種不同啤酒的所有酒吧

我的表是

塞爾斯(酒吧,啤酒價格) - 巴 - 外鍵.. 酒吧(名稱,地址) - 命名的主鍵。

我想到了這樣的事情但dosent似乎工作...

Select A.bar As bar , B.bar as bar 
From Sells AS A, Sells AS B 
Where A.bar = B.bar and A.beer <> B.beer 
Group By(A.beer) 
Having Count(Distinct A.beer) >= 2 

這是正確的SQL查詢?

+0

那麼有一個主題會吸引人們! :) – 2010-05-03 18:58:54

回答

2

我會做這種方式:

Select A.bar 
From Sells AS A 
JOIN Sells AS B ON (A.bar = B.bar AND A.price = B.price 
    AND A.beer <> B.beer) 
JOIN Sells AS C ON (A.bar = C.bar AND A.price = C.price 
    AND A.beer <> C.beer AND B.beer <> C.beer) 

在MySQL尤其是加入的解決方案是可能比GROUP BY更有效。

1
Select ... 
From Bars As B 
Where Exists (
       Select 1 
       From Sells As S1 
       Where Exists (
           Select 1 
           From Sells As S2 
           Where S2.bar = S1.bar 
            And S2.beer <> S1.beer 
            And S2.price = S1.price 
           ) 
        And S1.Bar = B.name 
       Having Count(*) = 3  
       )