php - 如果在使用连接时未找到行,则 SQL 求和为 0

标签 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

最佳答案

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

关于php - 如果在使用连接时未找到行,则 SQL 求和为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24591618/

相关文章:

php FILE POST上传而不保存

php - 对两个表进行模糊匹配的选择查询

mysql - 关闭 JDO 中的 sql 日志记录。

php - 调用函数时如何省略中间参数的默认值?

php - 即使用户没有在注册表单上注册,我的 PID 也会自动递增

mysql - 通过 cron 将参数传递给 SQL 脚本

mysql - 如何在 char 列中选择真正的 MAX 整数?

MySQL - 具有 'Or' 条件的选择查询的列索引或复合索引

mysql - MySQL 'NOT' 关键字中的哪些子句可以与哪些子句一起使用?确实特别是在 MySQL 中

sql - 我们如何检查表是否有索引?