开发者

mySQL return not empty field

开发者 https://www.devze.com 2022-12-18 11:42 出处:网络
I have two fields, but I want to return only the non-empty one. select firstname, lastname, (if firstname != empty, then firstname else lastname) as name from users;

I have two fields, but I want to return only the non-empty one.

select firstname, lastname, (if firstname != empty, then firstname else lastname) as name from users;

How do I go about doing something like a开发者_StackOverflow社区bove. Am not sure what should be inside the round brackets. I don't want to use PHP post-processing.


There are several ways you can do this in MySQL.

You can use the coalesce() function which returns the first non-null value among its arguments.

select coalesce(firstname, lastname) as name from users;

Alternatively, you could use a case statement:

select case when firstname is not null then firstname else lastname end as name from users;

Or you could use the if() function:

select if(firstname is not null, firstname, lastname) as name from users;

Or you could use the ifnull() function:

select ifnull(firstname, lastname) as name from users;


This works for both null values as well as empty strings ('')

SELECT IF(LENGTH(firstname), firstname, lastname) as name from users;
0

精彩评论

暂无评论...
验证码 换一张
取 消