SQL Replace last 2 chars if last 2 chars matches

淺唱寂寞╮ 提交于 2019-12-13 18:43:33

问题


I hope someone can help me. I have a column with 160.000 rows. A lot of those column values (permalinks) end with "-2" which is unneccesary so I want to remove them. But I can't get it to work.

I tried it with the following query:

UPDATE wp_pods_cars
SET permalink = Replace(permalink,'-2','')
WHERE RIGHT( 'permalink' , 2 ) = '-2';

This query seems to be valid but the RIGHT() seems to make troubles. Probably it can just be used for a SELECT and not in a WHERE-clause.

I was thinking about Regex, but I didn't get that to work either. I already fail in finding the right regular expression for my case.


回答1:


You have single quotes around the column name, so you are comparing a constant string in the where clause. The version that comes closer to working is:

UPDATE wp_pods_cars
    SET permalink = Replace(permalink,'-2','')
    WHERE RIGHT(permalink, 2 ) = '-2';

However, I would write this as:

UPDATE wp_pods_cars
    SET permalink = LEFT(permalink, length(permalink) - 2) 
    WHERE permalink LIKE '%-2';

The -2 might appear at other places in the string and you don't want to remove all occurrences.




回答2:


First of all remove quotes from column name as per comment by Oleg .This may be another solution with your criteria, the MySQL SUBSTRING function extracts portion of a string, CHAR_LENGTH function calculates the number of characters in the string & finally assign it to permalink.

 UPDATE wp_pods_cars
  SET permalink = SUBSTRING(permalink, 1, CHAR_LENGTH(permalink) - 2) 
 WHERE permalink LIKE '%-2';

More About:

SUBSTRING

CHAR_LENGTH



来源:https://stackoverflow.com/questions/30413216/sql-replace-last-2-chars-if-last-2-chars-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!