问题
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