sql姓氏逗号首先是null检查

时间:2013-09-19 23:51:10

标签: mysql

我在数据库中有三列代表一个人的名字,中间名和姓:

            People
|------------------------------------------|
| First_Name  |  Last_name    | Middle_name|
|------------------------------------------|
|  John       |  Hansen       |     T      |
|   NULL      |  Smith        |    NULL    |
|  Jacob      |    NULL       |     J      |
|  Michael    |  Johnson      |    NULL    |
|------------------------------------------|

获得null安全的最佳方法是Last,First Name + Middle Name。所以从上面的列表我会得到:

Hansen, John T
Smith
Jacob J
Johnson, Michael

到目前为止,我已经:

select concat_ws(', ', name_last, concat_ws(' ', name_first, name_middle)) as name from entity;

但它让我跟踪,,我不想要它们。

2 个答案:

答案 0 :(得分:5)

如果任何参数为CONCAT,您可以使用NULL将返回NULL的事实:

SELECT COALESCE(CONCAT(last_name, ', ', first_name), last_name, first_name)
FROM People

SQL Fiddle Demo


或者,既然您已编辑了问题以添加Middle_name列:

SELECT COALESCE(CONCAT(last_name, ', ', COALESCE(CONCAT(first_name, ' ', middle_name),first_name,middle_name)), 
                last_name, 
                COALESCE(CONCAT(first_name, ' ', middle_name),first_name,middle_name))
FROM People

SQL Fiddle Demo

答案 1 :(得分:0)

反过来说: 你有一个包含" firstname middlename lastname"的全名列。 并希望按姓氏显示它

让它变得有效,至少它对荷兰名字很有用(" van der Boogert"还有单身(艺术家)名字。

此示例修剪了额外空格的anmes,然后计算全名中的空格数量,因此当它只有一个名称(艺术家名称)时,没有逗号是位置

SELECT
    TRIM(fullname) as originalfullname, 
    length(trim(fullname)) -length(replace(TRIM(fullname), ' ', '')) AS countedzeros,
    SUBSTRING_INDEX(TRIM(fullname), ' ', length(TRIM(fullname)) -length(replace(TRIM(fullname), ' ', '')))  AS first_name,
    SUBSTRING_INDEX(TRIM(fullname),  ' ', -1) AS last_name,
    CONCAT(
        SUBSTRING_INDEX(TRIM(fullname),  ' ', -1),
        IF(length(TRIM(fullname)) -length(replace(TRIM(fullname), ' ', '')),', ',''),
      SUBSTRING_INDEX(TRIM(fullname), ' ', length(TRIM(fullname)) -length(replace(TRIM(fullname), ' ', '')))
    ) as dispayname
    FROM catalog
    group by fullname


/*
Theo van den Boogaart => Boogaart, Theo van den
Hergé => Hergé
Jhonny Smith => Smith, Johnny

*/