选择列值(如果不为null),否则使用另一个列值 [英] Select column value if not null else use another column value
问题描述
我在mysql表中有2列:a和b. a始终为字符串值,b有时为字符串值,有时为null.
I have 2 columns in mysql table: a and b. a is allways string value and b is sometimes a string value and sometimes it is null.
如何构造mysql SELECT,以便如果b不为null则采用b,否则采用a.
How to construct a mysql SELECT so that the b would be taken if it is not null and a would be taken otherwise.
我试图用concat制作一些魔术,如果...那么没有成功...
I tried to make some magic with concat and if...then with no success...
更新-扩展我的问题,是否有一个函数可以像Ifnull一样工作,但可以用于null和空值?
UPDATE - To extend my question, is there a function that would work like Ifnull but would work for null AND empty values?
推荐答案
使用
如果expr1不为NULL,则IFNULL()返回expr1;否则返回expr2.
If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. 这是MySQL特有的功能.您也可以以相同的方式使用 COALESCE .这将在更多数据库中工作,但在MySQL中的性能要比IFNULL稍差. This is a MySQL specific function. You can also use COALESCE in the same way. This will work in more databases but it has slightly worse performance in MySQL than IFNULL. 这篇关于选择列值(如果不为null),否则使用另一个列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!