我对此查询遇到了很多麻烦,但我觉得我不应该这样做。我已将问题转换为更简单的问题,因此更容易理解。
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
答案 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