如何在 MYSQL 查询中将名字和姓氏作为全名?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3251600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:33:46  来源:igfitidea点击:

How do I get first name and last name as whole name in a MYSQL query?

sqlmysql

提问by alex

I want to be able to do something like this

我希望能够做这样的事情

SELECT `first_name` + " " + `last_name` as `whole_name` FROM `users`

So basically I get one column back whole_namewhich is first_nameand last_nameconcatenated together with a (space).

所以基本上,我得到一个回whole_namefirst_namelast_name与连接在一起(空间)。

How do I do that in SQL, or more specifically, MySQL ?

我如何在 SQL 中做到这一点,或者更具体地说,在 MySQL 中?

回答by gtiwari333

When you have three columns : first_name, last_name, mid_name:

当您有三列时:first_name、last_name、mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

回答by Ritesh Yadav

You can use a query to get the same:

您可以使用查询来获得相同的结果:

SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;

Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"

注意:如果所有列都有某个值,如果任何人为 null 或为空,则此查询返回,那么它将为所有返回 null,表示 Name 将返回“NULL”

To avoid above we can use the IsNullkeyword to get the same.

为了避免上述情况,我们可以使用IsNull关键字来获得相同的结果。

SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;

If anyone containing null value the ' ' (space) will add with next value.

如果有人包含空值,则 ' '(空格)将与下一个值相加。

回答by rim

rtrim(lastname)+','+rtrim(firstname) as [Person Name]
from Table

the result will show lastname,firstname as one column header !

结果将显示姓氏,名字作为一个列标题!