我有一张产品表和一张产品评论表。当我显示产品库存时,我希望通过评论评分对它们进行排序,但是如何使用另一个表中的值对一个表进行排序?
产品
product_id | ...
------------------
1 ...
2 ...
3 ...
4 ...
...
评论
review_id | product_id | user_id | score | ...
------------------------------------------------
1 2 104 5 ...
2 1 98 4 ...
3 2 76 2 ...
4 3 119 5 ...
... ... ... ...
我的产品清单按照以下汇总评论得分的降序排列:
SELECT product_id, SUM(score)/(COUNT(*)*1.0) AS scoring
FROM reviews
GROUP BY product_id
ORDER BY scoring DESC
但是我想从这个排序中对表products
进行排序,因为单独这是没用的。
答案 0 :(得分:1)
如果您使用JOIN
表进行products
,然后将其排序为
select p.*, tab.scoring
from products p
INNER JOIN
(
SELECT product_id, SUM(score)/(COUNT(*)*1.0) AS scoring
FROM reviews
GROUP BY product_id
) tab on p.product_id = tab.product_id
ORDER BY tab.scoring DESC