COALESCE() for blank (but not null) fields

我的梦境 提交于 2019-11-30 00:50:19

问题


I have two fields that I'm comparing with MySQL's function COALESCE(). For example, COALESCE(Field1, Field2). The problem is, Field1 is sometimes blank but not null; since it's not null COALESCE() selects Field1, even though its blank. In that case, I need it to select Field2.

I know I can write a if-then-else (CASE) statement in the query to check for this, but is there a nice simple function like COALESCE() for blank-but-not-null fields?


回答1:


SELECT IFNULL(NULLIF(Field1,''),Field2)

NULLIF returns a NULL if Field1 is blank, while IFNULL returns Field1 if it's not blank or NULL and Field2 otherwise.




回答2:


You can use a CASE expression:

CASE WHEN Field1 <> '' THEN Field1 ELSE Field2 END



回答3:


I know I'm late to the party here, but there is a way to do this while still using COALESCE(). This would then work if your value was NULL or ''.

Select COALESCE(NULLIF(Field1,''), Field2)


来源:https://stackoverflow.com/questions/13235847/coalesce-for-blank-but-not-null-fields

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!