【发布时间】:2021-04-03 10:18:12
【问题描述】:
我有 3 张这样的桌子
订单表:
| id | product_id | status | created_at |
|----| ---------- | ------ | ---------- |
| 1 | 1 | done | 1607431726 |
| 2 | 7 | done | 1607431726 |
| 3 | 8 | done | 1607431726 |
产品表:
| id | user_id | title | description | created_at |
|----| ------- | ----------- | ------------- | ---------- |
| 1 | 1 | product 1 | description 1 | 1607431726 |
| 7 | 3 | product 2 | description 1 | 1607431726 |
| 8 | 3 | product 3 | description 1 | 1607431726 |
评分表:
| id | client_id | content_type | content_id | rating | created_at |
|----| --------- | ------------ | ---------- | ------ | ---------- |
| 1 | 5 | user | 1 | 5 | 1607431726 |
| 2 | 4 | user | 3 | 5 | 1607431726 |
| 3 | 5 | user | 3 | 4 | 1607431726 |
从上面的 3 个表中,我想得到 1 个结果,其中有一个字段 average_rating/user、total order/user,我想按 average_rating 和 total_rating DESC 排序。大致是这样的结果:
| user_id | average_rating | total_order |
| ------- | -------------- | ----------- |
| 1 | 5.0 | 1 |
| 3 | 4.5 | 2 |
这是我的查询:
SELECT b.user_id, round(avg(c.rating), 1) as total_rating, COUNT(a.id) as total_order
FROM orders a
LEFT JOIN products b ON a.product_id=b.id
LEFT JOIN ratings c ON c.content_id=b.user_id
WHERE a.status = 'done'
AND c.content_type = 'user'
GROUP BY b.user_id, c.content_id;
但是使用我的查询,user_id 1 的总订单返回 1,user_id 3 的总订单返回 4,结果是:
| user_id | average_rating | total_order |
| ------- | -------------- | ----------- |
| 1 | 5.0 | 1 |
| 3 | 4.5 | 4 |
我尝试过INNER JOIN、LEFT OUTER、RIGHT OUTER、RIGHT JOIN,但结果是一样的。
谁能帮帮我?
【问题讨论】:
-
这是常见的连接乘法。计算子查询中的聚合然后加入。
标签: mysql sql count left-join aggregate-functions