2016-04-22 75 views
1

之間,其中平均收視我有2個表:選擇ID的

表 「BIZ」 並表 「biz_rating」

BIZ

  • biz_id(INT)
  • 名(VARCHAR )

biz_rating

  • biz_rating_id(INT)
  • biz_id(INT)
  • 等級(INT)

我想查詢選擇ALL BIZ行,其中平均評級是1-2之間,或3-4,或< 5或> 5(評級是從0到5的數字)。

我從字面上沒有想法如何開始。

我現在是這樣的:

SELECT 
    biz_id 
FROM 
    biz 
WHERE 
    biz_id IN 
    (SELECT biz_id FROM biz_rating WHERE AVG(rating) BETWEEN 0 AND 5) 
ORDER BY 
    biz_id ASC 

但是這根本不工作。

+0

添加GROUP BY並從子選擇中從WHERE切換到HAVING。 – jarlh

回答

1

您可以加入表,如果你想要的名字與編號

select biz_id,name,b2.avgrating 
from BIZ as B1, 
(select biz_id as bid, avg(rating) as avgrating 
from biz_rating 
group by biz_id 
having avg(rating) between 0 and 5) as B2 

where B1.biz_id=B2.bid 

這一起,如果你想

也將選擇平均評分
0

只需使用聚合。你甚至都不需要這樣的join

select br.biz_id 
from biz_rating br 
group by br.biz_id 
having avg(rating) between 1 and 2; -- or whatever limits you want