我对这个查询有很多问题,但我真的觉得我不应该这样做。我已经把我的问题转换成一个更简单的问题,这样就更容易理解了。

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

最佳答案

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

09-26 20:55