[英]mysql concat remove trailing dash if it exists
I have a select that concats several columns together separating them with a dash "-" character. 我有一个选择,将几个列连在一起,并用破折号“-”将它们分开。 The last column 'description' may or may not have a value. 最后一列“说明”可能有也可能没有值。 If it does, all is good, if it doesn't, I end up with a "-" at the end. 如果可以,那么一切都很好,如果不能,那么我最后会以“-”结尾。 How can I get rid of the last character only if it is a "-"? 仅当最后一个字符为“-”时,如何才能删除它?
SELECT CONCAT(locationid,'-',city,'-',state,'-',country,'-',description) FROM sys_locations ORDER BY locationid
Example with 'description' column populated: AUC01-Aurora-CO-US-DC 带有“描述”列的示例:AUC01-Aurora-CO-US-DC
Example with 'description' column empty: AUM01-Auburn Hills-MI-US- <- notice trailing dash. “描述”列为空的示例:AUM01-Auburn Hills-MI-US- <-注意尾随破折号。
Thanks, David 谢谢大卫
你可以这样
SELECT CONCAT(locationid,'-',city,'-',state,'-',country,IF(description is null,'',concat('-', description))) FROM sys_locations ORDER BY locationid
To handle both NULL and '', try this: 要同时处理NULL和'',请尝试以下操作:
SELECT CONCAT(locationid,'-', city, '-', state, '-', country, case when description IS NULL or description = '' then '' else '-' end, description)
FROM sys_locations ORDER BY locationid
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.