开发者

MySQL: if field is empty assign a value

开发者 https://www.devze.com 2023-01-31 23:35 出处:网络
Here\'s my query: 开发者_如何学编程$sql = \"SELECT u.PHONE , u.STATE , if (uo.CHANNEL=\'\',\'web\',channel) as TYPE FROM user

Here's my query:

开发者_如何学编程$sql = "SELECT u.PHONE , u.STATE , if (uo.CHANNEL='','web',channel) as TYPE FROM user
LEFT JOIN user_oferts uo ON u.PHONE=uo.PHE_USER 
WHERE (u.STATE='active') ";

And it is working great, I get what I want BUT for channel that is empty.

I need channel to be "web" if it is not "wap", this way channel will not be empty or null or nothing. How can I do that? What am I doing wrong?

Thanks a lot


select 
...
case when channel = '' then 
   web 
else 
   channel 
end as TYPE....

using the CASE statement.

i.e. for your case

$sql = "SELECT u.PHONE , u.STATE 
, case when coalesce(uo.CHANNEL, '') = '' then 'web' else channel end as TYPE 
FROM user
LEFT JOIN user_oferts uo ON u.PHONE=uo.PHE_USER 
WHERE (u.STATE='active') ";

Edit: added coalesce to deal with possible NULL values.


Any reason why this can't work?

$sql = "SELECT u.PHONE , u.STATE , if (uo.CHANNEL='wap','wap','web') as TYPE FROM user
LEFT JOIN user_oferts uo ON u.PHONE=uo.PHE_USER 
WHERE (u.STATE='active') ";

MySQL doesn't like comparing a null to a string, so you could either nest in another if statement testing uo.CHANNEL IS NULL, or rather, alter your table so it can't be null, and give it a default value of 'wap'.

0

精彩评论

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