左JOIN给出不正确的总和结果

时间:2016-12-27 13:24:24

标签: php mysql

我有两个表(daily_book和extra_cost)所以结构是

daily_book

db_id | refund                
1     |  7161                 
2     |  5980                 

extra_cost

ec_id  |  db_id    | cost
1      |   1       |  156
2      |   1       |  123
3      |   2       |  100
4      |   2       |  120 

因此,我获得了一行中的总退款金额和总费用值。

所以我的查询是

$sql = "SELECT SUM(d.refund) AS refund, SUM(e.cost) AS e_cost FROM `daily_book` d LEFT JOIN extra_cost e ON (d.db_id = e.db_id) WHERE d.db_id > 0";

我得到的结果是26,282退款和499总费用;这是不正确的。

我希望结果是13,141退款和499总费用。

1 个答案:

答案 0 :(得分:1)

这里没有神秘感。您正在汇总多行以获得退款。您需要单独进行聚合。在MySQL中,这有点麻烦,但这里有一种方法:

SELECT dd.refund, SUM(e.cost) AS e_cost
FROM daily_book d LEFT JOIN
     extra_cost e
     ON (d.db_id = e.db_id) CROSS JOIN
     (SELECT SUM(d.refund) as refund FROM daily_book d WHERE d.db_id > 0) dd
WHERE d.db_id > 0;