我有一个选择,它将多个列连接在一起,用短划线“ - ”字符分隔它们。最后一列“描述”可能有也可能没有值。如果确实如此,一切都很好,如果没有,我最后会得到一个“ - ”。如果它是“ - ”,我怎么能摆脱最后一个字符?
SELECT CONCAT(locationid,'-',city,'-',state,'-',country,'-',description) FROM sys_locations ORDER BY locationid
填充'description'列的示例: AUC01极光-CO-US-DC
'description'列为空的示例: AUM01-Auburn Hills-MI-US-< - notice trailing dash。
谢谢, 大卫
答案 0 :(得分:2)
您需要NULLIF
:
SELECT CONCAT_WS('-', locationid, city, state, country, NULLIF(description, ''))
FROM sys_locations ORDER BY locationid
答案 1 :(得分:0)
你可以这样做
SELECT CONCAT(locationid,'-',city,'-',state,'-',country,IF(description is null,'',concat('-', description))) FROM sys_locations ORDER BY locationid
答案 2 :(得分:0)
要处理NULL和'',请尝试:
SELECT CONCAT(locationid,'-', city, '-', state, '-', country, case when description IS NULL or description = '' then '' else '-' end, description)
FROM sys_locations ORDER BY locationid