select
p.product_id product_id,
product_name,
sum(quantity) total_quantity,
round(avg(avg_rating),2) average_rating
from products_underline p
right join sales_underline s on p.product_id=s.product_id and year(sale_date)='2024'
join (
select product_id,
avg(rating) avg_rating
from reviews_underline
group by product_id
having avg(rating)<=4
) r on s.product_id=r.product_id
group by p.product_id
order by average_rating,product_id
1.解决因为多表连接出现笛卡尔积导致结果虚高的情况
应尝试更改表链接方式和对子表预处理之后再进行连接,把原来在主查询中的筛选条件放到对子表的预处理中
2.需要对子表中的聚合函数进行重命名之后才能在主查询中应用,因此 avg(rating) avg_rating是必要的,否则如果按round(avg(rating),2) average_rating就会出现找不到对应的列名的情况。因为虽然子查询中已经有了avg(rating)的列,但是在主查询中avg是以聚合函数的形式出现的,他不能作为列名进行引用,因此如果想引用子查询中聚合后的结果的话,必须为子查询的聚合结果设置别名。

京公网安备 11010502036488号