任何人都可以简化此 mysql 查询
any one can simplify this mysql query
任何人都可以简化此 MYSQL 查询
相同 table 我想将具有 1 类型的值的总和减去另一种类型
例如:sum( type1 ) - sum (type 2)
SELECT (SELECT sum(exp_amount) FROM `expenses` WHERE `account_id` = 1 && `type_id` = 2)
- (SELECT sum(exp_amount) FROM `expenses` WHERE `account_id` = 1 && `type_id` = 1) AS balance FROM `expenses`
LIMIT 0 , 1
指导我如何在 Cake 中处理此查询 php 注意:不要直接使用此查询 ->query (...)
您可以通过使用下面基于案例的聚合
单次扫描table来获得余额
SELECT Coalesce(sum(CASE WHEN type_id=2 THEN exp_amount END), 0) - Coalesce(sum(CASE WHEN type_id =1 THEN exp_amount END),0) AS balance
FROM expenses
WHERE account_id = 1
AND type_id IN (1,2)
任何人都可以简化此 MYSQL 查询
相同 table 我想将具有 1 类型的值的总和减去另一种类型
例如:sum( type1 ) - sum (type 2)
SELECT (SELECT sum(exp_amount) FROM `expenses` WHERE `account_id` = 1 && `type_id` = 2)
- (SELECT sum(exp_amount) FROM `expenses` WHERE `account_id` = 1 && `type_id` = 1) AS balance FROM `expenses`
LIMIT 0 , 1
指导我如何在 Cake 中处理此查询 php 注意:不要直接使用此查询 ->query (...)
您可以通过使用下面基于案例的聚合
单次扫描table来获得余额SELECT Coalesce(sum(CASE WHEN type_id=2 THEN exp_amount END), 0) - Coalesce(sum(CASE WHEN type_id =1 THEN exp_amount END),0) AS balance
FROM expenses
WHERE account_id = 1
AND type_id IN (1,2)