我有这样的查询类型:
SELECT table1.field1, table1.field2, table2.field3
FROM table1
LEFT JOIN table2 ON (...)
由于左连接,我有时有table2。field3空
之后在我的php脚本循环中我手动重新定义
...
$row['field3'] = ($row['field3'] === null) ? 'undefined' : $row['field3'];
...
但是我怎么能得到这个'未定义'在我的结果集中?
我一直在寻找答案,COALESCE似乎有效,但它有一些奇怪的逻辑,有很多很多的论点。好像做我想做的事,但不知怎么的奇怪…
我感兴趣的是,如果有另一种简单的方法来取代我的NULL与'未定义'?
你不应该害怕COALESCE…好的。
但是,还有其他方法:
-
使用IF &为空
选择表。field1,表1。field2,如果(表二。field3 IS NULL, 'undefined', table2.field3) AS field3
-
或者更简单,使用IFNULL(我相信你会喜欢它)
选择表。field1,表1。field2, IFNULL(表二。
https://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html function_ifnull
Select
case when table1.field1 is null then
case when table1.field2 is null then 'undefined'
else table1.field2 end
else table1.field1 end as field1
from tablename
当你想检查更深层次的条件时,可以使用嵌套的大小写