我想创建一个将连接用户的全名的视图。如果用户具有扩展名,则会将其与全名连接。
例如:
John May Brown(Fname,Mname,Lname)
,扩展名为
John May Brown Jr.(Fname,Mname,Lname,ExtName)
我的代码:
Create view viewforum (
SELECT A.*, CONCAT(B.Fname," ",B.Mname," ",B.Lname," ",B.ExtName) AS Fullname
FROM forum_table A INNER JOIN user_table B
WHERE A.user_id = B.user_id
);
输出:
Fullname列下的所有数据均为NULL
,因为某些用户信息上没有扩展名。所以输出是NULL
。
我如何制定条件?
答案 0 :(得分:0)
为了消除nulls
:
Create view viewforum (SELECT A.*,
CONCAT(
B.Fname,
" ",
COALESCE(B.Mname, ""),
" ",
B.Lname," ",
COALESCE(B.ExtName,"")
) AS Fullname FROM forum_table A INNER JOIN user_table B WHERE A.user_id = B.user_id);
COALESCE
将从值列表中选择第一个非空值。如果COALESCE(B.ExtName, "")
为B.ExtName
Null
会产生空字符串
答案 1 :(得分:0)
您可以使用IFNULL来处理空值
Create view viewforum
( SELECT A.*, CONCAT(IFNULL(B.Fname," ")," ",IFNULL(B.Mname," ")," ",IFNULL(B.Lname," ")," ",IFNULL(B.ExtName," ")) AS Fullname
FROM forum_table A INNER JOIN user_table B
WHERE A.user_id = B.user_id
);
将返回没有空问题的所需结果