Return 0 if field is null in MySQL(如果字段在 MySQL 中为 null,则返回 0)
问题描述
在 MySQL 中,如果总计"字段为 NULL,是否可以将它们设置为零?
In MySQL, is there a way to set the "total" fields to zero if they are NULL?
这是我所拥有的:
SELECT uo.order_id, uo.order_total, uo.order_status,
(SELECT SUM(uop.price * uop.qty)
FROM uc_order_products uop
WHERE uo.order_id = uop.order_id
) AS products_subtotal,
(SELECT SUM(upr.amount)
FROM uc_payment_receipts upr
WHERE uo.order_id = upr.order_id
) AS payment_received,
(SELECT SUM(uoli.amount)
FROM uc_order_line_items uoli
WHERE uo.order_id = uoli.order_id
) AS line_item_subtotal
FROM uc_orders uo
WHERE uo.order_status NOT IN ("future", "canceled")
AND uo.uid = 4172;
数据很好,除了NULL字段应该是0.
The data comes out fine, except the NULL fields should be 0.
如何在 MySQL 中为 NULL 返回 0?
How can I return 0 for NULL in MySQL?
推荐答案
使用 IFNULL:
IFNULL(expr1, 0)
来自文档:
如果 expr1 不为 NULL,IFNULL() 返回 expr1;否则返回 expr2.IFNULL() 返回数字或字符串值,具体取决于使用它的上下文.
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
这篇关于如果字段在 MySQL 中为 null,则返回 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如果字段在 MySQL 中为 null,则返回 0
基础教程推荐
- 是否可以执行按位分组功能? 2021-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 在 SQL 中连接多个表 2021-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
