如果没有找到行,则SQL汇总为0,同时使用连接

时间:2014-07-06 00:15:44

标签: php mysql sql

我对此查询遇到了很多麻烦,但我觉得我不应该这样做。我已将问题转换为更简单的问题,因此更容易理解。

flowers_table
+---------------+-----------+
| flower_id     | name      |
+---------------+-----------+
| 1             | Tulips    |
| 2             | Rose      |
| 3             | Sun Flower|
| 4             | Orchids   |
+---------------+-----------+

transaction_table
+------------+------------------+
| trans_id   |  flower_id | sold|
+------------+------------------+
| 1          |    1       | 2   |
| 2          |    1       | 10  |
+------------+------------+-----+

结果:

+---------------+-----------+
| flower_id     | sold      |
+---------------+-----------+
| 1             | 12        |
| 2             | 0         |
| 3             | 0         |
| 4             | 0         |
+---------------+-----------+

这就是我想出来的。

SELECT flower_id.flower_table, COALESCE(SUM(transaction_table.sold), 0) AS sold
FROM flowers_table, transaction_table
Where flowers_table.flower_id = transaction_table.flower_id 
GROUP by flower_id

1 个答案:

答案 0 :(得分:1)

SELECT flower_id.flower_table, COALESCE(SUM(transaction_table.sold), 0) AS sold
FROM flowers_table LEFT JOIN transaction_table on flowers_table.flower_id = transaction_table.flower_id 
GROUP by flowers_table.flower_id