MySQL按不同表中的多列求和排序

标签 mysql sql

我有 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 的总和对用户进行排序?

谢谢!

最佳答案

由于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

关于MySQL按不同表中的多列求和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30393041/

相关文章:

mysql - 使用 where 条件过滤 View

java - 需要用hibernate dao实现方法保存两个来自不同jsp页面的有外键关系的表

sql - MySQL 恢复 - 带前缀的数据库表和不带前缀的 SQL 脚本

mysql - 将 null 更新为 not null

mysql - 索引与自动增量 ID 设置为 PK

sql - 转换为双引号类型的不一致

mysql - 带有 Mysql 主/从的 Datamapper

mysql - (服务器端)准备语句对 MySQL 5.5+ 查询计划的影响

java - 应用特定数据库

sql - 获取聚合数据的 UNION ALL 的替代方案