gpt4 book ai didi

Sql 在两个表之间加入一个组

转载 作者:行者123 更新时间:2023-12-04 23:47:04 26 4
gpt4 key购买 nike

我对 SQL 非常陌生,我一直在解决这个问题几个小时,我很接近但还没有完全到位:

三 table

类别

西德
名称

产品

pid
cid
pname
brand
price

评论
rid
userid
pid
rdate
score rcomment

我在尝试着
  • 返回产品名称和平均分。
  • 返回 TV 类别下平均评分高于 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';

    这是一个 fiddle :
    http://sqlfiddle.com/#!4/a6b30/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;
  • 在以下查询中,我使用子查询仅选择平均分数 >= 4 的项目,使用 HAVING条款。然后我只选择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);
  • 关于Sql 在两个表之间加入一个组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39688211/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com