[英]case statements with two conditions of two different fields
this is my scenario... i would like to check if the member has mobile in one table, if yes then to display his mobile.. else to check if he has landline phone from another table... if yes then to display landline... else blank. 这是我的情景......我想检查会员是否在一张桌子上移动,如果是,则显示他的手机..否则检查他是否有来自另一张桌子的固定电话...如果是,则显示固定电话......其他空白。 not sure if we can use case statement on comparing two different fields
不确定我们是否可以在比较两个不同的字段时使用case语句
SELECT a.name as name, b.name as parent_name, a.mobile, b.phone,
case
when a.mobile is not null or a.mobile<>'' then a.mobile
else b.phone
end
as phone
FROM family_member a join family_header b where a.name='sam' and a.id=b.match_key;
please guide me.. only the first case statement is executed and a.mobile is displayed when available.. but if mobile is not available, the landline is NOT displayed.. 请指导我..只执行第一个案例陈述,并在可用时显示a.mobile ..但如果手机不可用,则不显示座机。
If mobile
is an empty string, it is not null
, so this condition matches all those records where a.mobile
is an empty string. 如果
mobile
是一个空字符串,则它not null
,因此该条件匹配a.mobile
为空字符串的所有记录。 So my guess is, none of your empty fields are null
. 所以我的猜测是,你的空字段都不是
null
。
Change the condition to: 将条件更改为:
when a.mobile is not null AND a.mobile<>'' then
Maybe even better: make the field not nullable, so it always contains a phone number or an empty string. 甚至可能更好:使该字段不可为空,因此它始终包含电话号码或空字符串。 Then you can simplify the condition to:
然后你可以简化条件:
when a.mobile<>'' then
SELECT a.name as name, b.name as parent_name, a.mobile, b.phone,
case
when a.mobile is not null or a.mobile<>'' then a.mobile
else (CASE
when b.phone is not NULL or b.phone<>'' then b.phone
else '')
end
as phone
FROM family_member a join family_header b where a.name='sam' and a.id=b.match_key;
我会推荐COALESCE。
COALESCE(a.mobile, b.phone, '')
CASE
is bound to a column only if that column is before the WHEN
otherwise is free 仅当该列位于
WHEN
之前, CASE
绑定到列,否则为WHEN
SELECT a.name as name, b.name as parent_name, a.mobile, b.phone
, CASE WHEN a.mobile is NOT NULL OR a.mobile<>'' THEN a.mobile
WHEN b.phone is NOT NULL OR b.phone<>'' THEN b.phone
ELSE ''
END AS phone
FROM family_member a
JOIN family_header b
WHERE a.name='sam'
AND a.id=b.match_key;
If the phone numbers can be an empty string or null then you will want to use a CASE
statement. 如果电话号码可以是空字符串或null,那么您将需要使用
CASE
语句。 Secondly I do believe you need to use AND
instead of OR
in the CASE
. 其次我相信你需要在
CASE
使用AND
而不是OR
。 Also, you did not JOIN
your tables properly: 此外,您没有正确
JOIN
表格:
SELECT a.name as name, b.name as parent_name,
CASE WHEN a.mobile is NOT NULL AND a.mobile <> '' THEN a.mobile
WHEN b.phone is NOT NULL AND b.phone <> '' THEN b.phone
ELSE '' END AS Phone
FROM family_member a
INNER JOIN family_header b ON a.id = b.match_key
WHERE a.name = 'sam'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.