我有 3 个表:
用户
| id | name |
|----|-------|
| 1 | One |
| 2 | Two |
| 3 | Three |
喜欢
| id | user_id | like |
|----|---------|-------|
| 1 | 1 | 3 |
| 2 | 1 | 5 |
| 3 | 2 | 1 |
| 4 | 3 | 2 |
翻译
| id | user_id | transaction |
|----|---------|-------------|
| 1 | 1 | -1 |
| 2 | 2 | 5 |
| 3 | 2 | -1 |
| 4 | 3 | 10 |
我需要为每个用户获取 likes.like 和 transations.transation 的总和,然后根据结果对其进行排序。
我能够为用户和喜欢的人做到这一点:
select users.*, sum(likes.like) as points
from `users`
inner join `likes` on `likes`.`user_id` = `users`.`id`
group by `users`.`id`
order by points desc
然后我像这样添加交易表:
select users.*, (sum(likes.like)+sum(transactions.`transaction`)) as points
from `users`
inner join `likes` on `likes`.`user_id` = `users`.`id`
inner join `transactions` on `transactions`.`user_id` = `users`.`id`
group by `users`.`id`
order by points desc
显示错误的结果。
我期待看到:
| id | name | points |
|----|-------|--------|
| 3 | Three | 12 |
| 1 | One | 7 |
| 2 | Two | 5 |
但改用这个:
| id | name | points |
|----|-------|--------|
| 3 | Three | 12 |
| 1 | One | 6 |
| 2 | Two | 5 |
那么,如何按 likes.like 和 transations.transation 的总和对用户进行排序?
谢谢!
最佳答案
由于transactions
和likes
之间不是一对一的关系,我认为您需要使用子查询:
select users.*,
(select sum(points) from likes where user_id = users.id) as points,
(select sum(transaction) from transactions where user_id = users.id) as transactions
from users
order by points desc
更新后对要求进行了更多解释:
select users.*,
(select sum(points) from likes where user_id = users.id) +
(select sum(transaction) from transactions where user_id = users.id) as points
from users
order by points desc
关于MySQL按不同表中的多列求和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30393041/