首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >和( col + col 2)如果col 1包含空

和( col + col 2)如果col 1包含空
EN

Stack Overflow用户
提问于 2022-12-02 19:11:17
回答 1查看 48关注 0票数 0
代码语言:javascript
复制
Input: 
Boxes table:
+--------+----------+-------------+--------------+
| box_id | chest_id | apple_count | orange_count |
+--------+----------+-------------+--------------+
| 2      | null     | 6           | 15           |
| 18     | 14       | 4           | 15           |
| 19     | 3        | 8           | 4            |
| 12     | 2        | 19          | 20           |
| 20     | 6        | 12          | 9            |
| 8      | 6        | 9           | 9            |
| 3      | 14       | 16          | 7            |
+--------+----------+-------------+--------------+
Chests table:
+----------+-------------+--------------+
| chest_id | apple_count | orange_count |
+----------+-------------+--------------+
| 6        | 5           | 6            |
| 14       | 20          | 10           |
| 2        | 8           | 8            |
| 3        | 19          | 4            |
| 16       | 19          | 19           |
+----------+-------------+--------------+
Output: 
+-------------+--------------+
| apple_count | orange_count |
+-------------+--------------+
| 151         | 123          |
+-------------+--------------+
Explanation: 
box 2 has 6 apples and 15 oranges.
box 18 has 4 + 20 (from the chest) = 24 apples and 15 + 10 (from the chest) = 25 oranges.
box 19 has 8 + 19 (from the chest) = 27 apples and 4 + 4 (from the chest) = 8 oranges.
box 12 has 19 + 8 (from the chest) = 27 apples and 20 + 8 (from the chest) = 28 oranges.
box 20 has 12 + 5 (from the chest) = 17 apples and 9 + 6 (from the chest) = 15 oranges.
box 8 has 9 + 5 (from the chest) = 14 apples and 9 + 6 (from the chest) = 15 oranges.
box 3 has 16 + 20 (from the chest) = 36 apples and 7 + 10 (from the chest) = 17 oranges.
Total number of apples = 6 + 24 + 27 + 27 + 17 + 14 + 36 = 151
Total number of oranges = 15 + 25 + 8 + 28 + 15 + 15 + 17 = 123
代码语言:javascript
复制
My answer:
SELECT 
SUM(b.apple_count +c.apple_count,0) AS apple_count, # IFNULL
SUM(b.orange_count+c.orange_count,0) AS orange_count
FROM Boxes b
LEFT JOIN Chests c
ON b.chest_id = c.chest_id

The expected answer:
SELECT 
SUM(b.apple_count +COALESCE(c.apple_count,0)) AS apple_count, # IFNULL
SUM(b.orange_count+COALESCE(c.orange_count,0)) AS orange_count
FROM Boxes b
LEFT JOIN Chests c
ON b.chest_id = c.chest_id

我的问题是,为什么我们必须在这个问题上使用COALESCE()或IFNULL()?

当使用SUM()时,0和null之间有什么区别?

我认为SUM()应该忽略MySQL中的null值,将6添加到苹果,15添加到橙色,即使在胸前表中添加了null?

EN

回答 1

Stack Overflow用户

发布于 2022-12-03 04:16:20

1+0=1

1+ null =空

这就是区别所在。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74660480

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档