【问题标题】:How to remove the seperator if all values are NULL in MySQL CONCAT_WS?如果 MySQL CONCAT_WS 中的所有值都为 NULL,如何删除分隔符?
【发布时间】:2013-09-17 23:39:51
【问题描述】:

我正在尝试使用 CONCAT_WS 生成主题行。但是,如果值为 null,我想忽略分隔符。

请看这个查询

SELECT
CONCAT_WS(" ",
CASE WHEN total_attempts > 0 THEN
CONCAT( call_code_title , " - ", total_attempts, "<sup>",
    CASE WHEN total_attempts = 2 THEN "nd"
    WHEN total_attempts = 3 THEN "rd"
    ELSE "th" END
, "</sup> attempt") ELSE call_code_title END
, "-", program_name) AS callSubject
FROM table

问题是当“program_name”为 NULL 时,字符串的末尾总是会有“-”。我不想连接“-”id program_name IS NULL

我该怎么做?

谢谢

【问题讨论】:

    标签: mysql concat-ws


    【解决方案1】:

    IFNULL(program_name, concat("-", program_name))

    SELECT
    CONCAT_WS(" ",
    CASE WHEN total_attempts > 0 THEN
    CONCAT( call_code_title , " - ", total_attempts, "<sup>",
        CASE WHEN total_attempts = 2 THEN "nd"
        WHEN total_attempts = 3 THEN "rd"
        ELSE "th" END
    , "</sup> attempt") ELSE call_code_title END
    , IFNULL(program_name, concat("-", program_name)) , " " ) AS callSubject
    FROM table
    

    【讨论】:

      【解决方案2】:
      SELECT
      CONCAT_WS(" ",
      CASE WHEN total_attempts > 0 THEN
      CONCAT( call_code_title , " - ", total_attempts, "<sup>",
          CASE WHEN total_attempts = 2 THEN "nd"
          WHEN total_attempts = 3 THEN "rd"
          ELSE "th" END
      , "</sup> attempt") ELSE call_code_title END
      , CONCAT("-", program_name) ) AS callSubject
      FROM table
      

      如果 program_name 为 NULL,则 CONCAT("-", program_name) 也将返回 NULL,CONCAT_WS 将通过忽略它所看到的单个 null 参数来正确处理。

      CONCAT() 如果任何参数为 NULL,则返回 NULL。

      ——http://dev.mysql.com/doc/refman/5.6/en/string-functions.html#function_concat

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-04-24
        • 2019-09-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多