0

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

请看这个查询

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

我怎么做?

谢谢

4

2 回答 2

0
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

于 2013-09-18T04:48:25.417 回答
0

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
于 2013-09-18T02:12:03.310 回答