这是我的情景...我想检查会员是否在一张桌子上移动,如果是,则显示他的手机..否则检查他是否有来自另一张桌子的固定电话...如果是的话显示固定电话......否则为空白。 不确定我们是否可以在比较两个不同的字段时使用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;
请指导我..只执行第一个案例陈述,并在可用时显示a.mobile ..但如果手机不可用,则不会显示座机。
答案 0 :(得分:1)
如果mobile
为空字符串,则为not null
,因此此条件匹配a.mobile
为空字符串的所有记录。所以我的猜测是,你的空字段都不是null
。
将条件更改为:
when a.mobile is not null AND a.mobile<>'' then
甚至可能更好:使该字段不可为空,因此它始终包含电话号码或空字符串。然后您可以将条件简化为:
when a.mobile<>'' then
答案 1 :(得分:0)
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;
答案 2 :(得分:0)
我会推荐COALESCE。
COALESCE(a.mobile, b.phone, '')
答案 3 :(得分:0)
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;
答案 4 :(得分:0)
如果电话号码可以是空字符串或null,那么您将需要使用CASE
语句。其次,我相信您需要在AND
中使用OR
而不是CASE
。此外,您没有正确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'