简体   繁体   English

相关表的SUM列

[英]SUM column of related tables

I've two tables, packages: 我有两个表,包:

id, ..., price fields id, ..., price字段

and users: 和用户:

id, ..., package_id

so every user has a package (users can have same package) that has a price. 所以每个用户都有一个有价格的包(用户可以拥有相同的包)。

and I want to calculate the SUM of the price of all users, how is the best way to do this? 而且我想计算所有用户的price和,这是最好的方法吗? preferably with only SQL. 最好只用SQL。 Having in mind that users table can have ~1m of users. 记住用户表可以有大约1米的用户。

SELECT SUM(price_x_user)
FROM (
    SELECT price AS price_x_user,
        users.id
    FROM users
    INNER JOIN packages ON packages.id = users.package_id
) AS users_package
Select id, SUM(price) from users t
Left join package p on p.id = t.id
group by t.id

When using a grouping function like SUM, it is required to group by. 使用像SUM这样的分组功能时,需要进行分组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM