2015-10-15 53 views
1

我有一個select將幾個列連接在一起,並用破折號「 - 」分隔。最後一列'描述'可能有也可能沒有值。如果是的話,一切都很好,如果不行的話,最後我會以「 - 」結尾。我如何才能擺脫最後一個字符,只有它是「 - 」?mysql concat如果存在,則刪除尾部破折號

SELECT CONCAT(locationid,'-',city,'-',state,'-',country,'-',description) FROM sys_locations ORDER BY locationid 

實施例與 '說明' 列填充: AUC01極光-CO-US-DC

實施例與 '說明' 列空: AUM01-Auburn Hills的-MI-US- < - 通知尾隨短劃線。

謝謝, 大衛

回答

0

你可以像下面這樣做

SELECT CONCAT(locationid,'-',city,'-',state,'-',country,IF(description is null,'',concat('-', description))) FROM sys_locations ORDER BY locationid 
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 
+0

完美工作。謝謝。 – user2934368

2

您需要NULLIF

SELECT CONCAT_WS('-', locationid, city, state, country, NULLIF(description, '')) 
FROM sys_locations ORDER BY locationid 
相關問題