简体   繁体   English

Mysql 从一个表列的总和减去另一个表列的总和

[英]Mysql from sum one table column subtract sum of another table column

Have 2 tables.有2张桌子。 In both tables exists columns for points and Id of user.在这两个表中都存在用于点和用户 ID 的列。 Want to sum all points for particular user in one table, then to sum in another and subtract from total of one table, total of another table.想要在一个表中为特定用户求和所有积分,然后在另一个表中求和并从一张表的总数中减去另一张表的总数。 Have 2 solutions (and also here http://sqlfiddle.com/#!9/f040a2/1 placed my testings).有 2 个解决方案(还有http://sqlfiddle.com/#!9/f040a2/1在这里放置了我的测试)。 Please advice which is better for performance.请建议哪个对性能更好。

The first solution.第一个解决方案。 Very clear and seems without "problems"非常清晰,似乎没有“问题”

SELECT 
( SELECT SUM(`PurchasedPoints`) FROM `first_table` WHERE `Id` = ? ) 
- 
( SELECT SUM(`SpendPoints`) FROM `second_table` WHERE `Id` = ? ) AS `RemainingPaidPoints`

Another solution with LEFT JOIN . LEFT JOIN的另一个解决方案。 Somewhere read, that LEFT JOIN is better for performance than subqueries.在某处读到, LEFT JOIN在性能方面比子查询更好。 But code looks complicated and not sure if it is reasonable to use it.但是代码看起来很复杂,不确定使用它是否合理。

SELECT SUM(`Ft`.`PurchasedPoints`) - `St`.`SpendPoints` AS `RemainingPaidPoints` 
FROM `first_table` `Ft` 

LEFT JOIN (
SELECT SUM(`SpendPoints`) AS `SpendPoints`, `Id` FROM `second_table` WHERE `Id` = ? 
GROUP BY `Id`
) `St` ON `Ft`.`Id` = `St`.`Id` 

WHERE `Ft`.`Id` = ? 

GROUP BY `Ft`.`Id` 

With both get the same result, but... which is better for performance etc., please?两者都得到相同的结果,但是......哪个对性能等更好,好吗?

JOIN works with tables, subqueries work with data sets. JOIN 适用于表,子查询适用于数据集。 That's why JOIN is faster than a subquery.这就是 JOIN 比子查询快的原因。

However, in both the queries you are running two separate SELECT queries.但是,在这两个查询中,您都在运行两个单独SELECT查询。 So performance-wise both are same.所以在性能方面两者都是相同的。 And, if you are counting the summation of a particular id then you don't need to use GROUP BY .而且,如果您正在计算特定id的总和,那么您不需要使用GROUP BY

SELECT SUM(`Ft`.`PurchasedPoints`) - SUM(`St`.`SpendPoints`) AS `RemainingPaidPoints` 
FROM `first_table` `Ft` 
LEFT JOIN `second_table` `St`
ON `Ft`.`Id` = `St`.`Id` 
WHERE `Ft`.`user_id` = ?

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

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