在 MYSQL 中执行 LEFT OUTER JOIN 时插入零而不是 NULL
Posted
技术标签:
【中文标题】在 MYSQL 中执行 LEFT OUTER JOIN 时插入零而不是 NULL【英文标题】:Inserting a Zero instead of NULL while performing LEFT OUTER JOIN in MYSQL 【发布时间】:2012-10-28 06:56:01 【问题描述】:在对两个表执行 LEFT OUTER JOIN 时,有没有办法插入零而不是 NULL?
假设我有这样的查询:
SELECT * FROM
(SELECT uID from Class) T1
LEFT OUTER JOIN
(SELECT pID from University) T2
ON T1.uID = T2.pID
CASE WHEN T1.uID IS NULL
THEN 0
ELSE T1.uID
END AS uID`
如果我错了,请纠正我
【问题讨论】:
【参考方案1】:使用ISNULL(field, 0)
,如果字段为NULL,则插入零
【讨论】:
对于 mysql,您的意思是ifnull()
而不是 isnull()
=)【参考方案2】:
类似:-
SELECT * FROM
(SELECT ifnull(uID,0) as uID from Class) T1
LEFT OUTER JOIN
(SELECT ifnull(pID,0) as pID from University) T2
ON T1.uID = T2.pID
【讨论】:
【参考方案3】:CASE WHEN a.fieldname IS NULL
THEN 0
ELSE a.fieldname
END AS fieldname
【讨论】:
SELECT * FROM (SELECT uID from Class) T1 LEFT OUTER JOIN (SELECT pID from University) T2 ON T1.uID = T2.pID CASE WHEN T1.uID IS NULL THEN 0 ELSE T1.uID END AS uID
如果我错了请纠正我
如果你想在 T1.UID 为空时加入 0,请使用下面的代码:SELECT * FROM (SELECT CASE WHEN uID IS NULL THEN 0 ELSE uID END AS uID from Class) T1 LEFT OUTER JOIN (SELECT pID from University) T2 ON T1.uID = T2.pID
以上是关于在 MYSQL 中执行 LEFT OUTER JOIN 时插入零而不是 NULL的主要内容,如果未能解决你的问题,请参考以下文章
MySQL 数据库中 left outer join 和 left join 啥区别?
关于mysql中的left join和left outer join的区别
mysql where not in to left outer join
MYSQL FULL OUTER JOIN - 使用 LEFT-UNION-LEFT JOIN 时的所有 NULL 结果