簡體   English   中英

Sql在兩個表之間加入一個group by

[英]Sql Join between two tables with a group by

我對SQL非常陌生,我一直在研究這個問題好幾個小時而且我非常接近,但不是很接近:

三張桌子

類別

cid cname

產品

pid
cid
pname
brand
price 

評論

rid
userid
pid
rdate
score rcomment

我在嘗試着

  • 返回產品名稱和平均分數。

  • 返回電視類別下的產品名稱,平均評分高於4.0

1:

select avg(score), review.pid
from review
join product
on review.pid = product.pid
group by review.pid;

2:

select * from product
join review
on product.pid = review.pid
where cid ='1';

這是一個小提琴: http ://sqlfiddle.com/#!4/ a6b30/1

  1. 您可以將pname添加到GROUP BY子句,然后添加到SELECT子句。 pid對於每個產品都是唯一的,因此它根本不會影響查詢,但是您可以將名稱添加到結果中。

     select avg(review.score), product.pname from review join product on review.pid = product.pid group by product.pname; 
  2. 在以下查詢中,我使用子查詢僅使用HAVING子句選擇平均得分> = 4的項目。 然后我只選擇出現在子查詢結果中的pid並添加cid='1'部分。

     select product.pname from product join review on product.pid = review.pid where cid ='1' and pid IN (SELECT pid FROM review GROUP BY pid HAVING AVG(score) >= 4); 

1。

select  p.pname, avg(r.score) 
from review r
join product p
on p.pid = r.pid
group by p.pname;

2.以下查詢返回TV類別下的產品ID和平均得分大於4.0的產品名稱

   select  p.pname,  avg(r.score)
    from 
        category c
    join product p on p.cid = c.cid 
    join review r  on r.pid = p.pid
    where c.cname = 'TV'
    group by 
      p.pname
    having  avg(r.score) > 4 ;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM