![](/img/trans.png)
[英]MySQL How to combine two tables (different fields) with two statements
[英]case statements with two conditions of 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;
请指导我..只执行第一个案例陈述,并在可用时显示a.mobile ..但如果手机不可用,则不显示座机。
如果mobile
是一个空字符串,则它not null
,因此该条件匹配a.mobile
为空字符串的所有记录。 所以我的猜测是,你的空字段都不是null
。
将条件更改为:
when a.mobile is not null AND a.mobile<>'' then
甚至可能更好:使该字段不可为空,因此它始终包含电话号码或空字符串。 然后你可以简化条件:
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, '')
仅当该列位于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;
如果电话号码可以是空字符串或null,那么您将需要使用CASE
语句。 其次我相信你需要在CASE
使用AND
而不是OR
。 此外,您没有正确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.