忽略MYSQL查询中的最后一个逗号

时间:2013-09-18 23:27:36

标签: mysql sql

SQL TABLE:产品

+--+------------+
|id| product_id |
+--+------------+
|1 | 689        |
|2 | 616,22,38  |
|3 | 666        |
|4 | 234,789    |
+--+------------+

SQL QUERY:

$id_pro= 23;
$sql = "UPDATE products SET product_id = CONCAT_WS(',',product_id, '$id_pro') WHERE id=3"; 

结果:

+--+------------+
|id| product_id |
+--+------------+
|1 | 689        |
|2 | 616,22,38  |
|3 | 666,23     |
|4 | 234,789    |
+--+------------+

问题:如果 product_id 以逗号结尾:

+--+------------+
|id| product_id |
+--+------------+
|1 | 689        |
|2 | 616,22,38  |
|3 | 666,       |
|4 | 234,789    |
+--+------------+

结果如下:

+--+------------+
|id| product_id |
+--+------------+
|1 | 689        |
|2 | 616,22,38  |
|3 | 666,,23    |
|4 | 234,789    |
+--+------------+

如何解决此问题,并使查询检测行是否以逗号结尾并忽略它?

1 个答案:

答案 0 :(得分:3)

尝试使用REPLACE()

 REPLACE(CONCAT_WS(',',product_id, '$id_pro'), ',,', ',')