MySQL按不同表中的多个列进行排序

时间:2015-05-22 09:25:22

标签: mysql sql

我有3张桌子:

用户

git submodule add -b <branch> <repository>

喜欢


| id | name  |
|----|-------|
| 1  | One   |
| 2  | Two   |
| 3  | Three |

Transations


| id | user_id | like  |
|----|---------|-------|
| 1  | 1       | 3     |
| 2  | 1       | 5     |
| 3  | 2       | 1     |
| 4  | 3       | 2     |

我需要为每个用户获取like.like和transations.transation的总和,然后按其结果对其进行排序。

我能够为用户和喜欢这样做:


| id | user_id | transaction |
|----|---------|-------------|
| 1  | 1       | -1          |
| 2  | 2       | 5           |
| 3  | 2       | -1          |
| 4  | 3       | 10          |

但后来我添加了这样的交易表:

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      |

那么,如何通过总和喜欢和喜欢和transations.transation排序用户?

谢谢!

1 个答案:

答案 0 :(得分:1)

由于transactionslikes之间不存在一对一的关系,我认为您需要使用子查询:

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