1

I need help replacing exact numbers in my database.

My table look likes this..

ID NAME    IMAGES
-------------------------------
1  person1  1,2,3...101,102,103

When I use

mysql_query("UPDATE table SET images = REPLACE(images, '3,', '') WHERE id = '1'");

It removes all the 3 from all numbers that end with 3..

13, = 1
23, = 2
113, = 11
4
  • 3
    You should not use a comma separated list in one of your fields. Normalize your database and store the images / image ID's in a separate table.
    – jeroen
    Mar 7, 2013 at 21:27
  • 1
    You should normalize your data. Much easier to work with that way.
    – John Conde
    Mar 7, 2013 at 21:27
  • 1
    Add a comma before the 3? mysql_query("UPDATE table SET images = REPLACE(images, ',3,', '') WHERE id = '1'"); Btw, previups comments are ok, you should normalize your data.
    – Babblo
    Mar 7, 2013 at 21:27
  • What do you want to happen? You tell us what is happening but not what you want the result to be. Mar 7, 2013 at 21:51

1 Answer 1

3

As has been mentioned already, the correct solution is to normalize the data. However if you are stuck with this table structure, you can still perform a single UPDATE statement using 3 CASE conditions to match the number at the beginning, middle, or end.

To remove it from the beginning or end of the list, you may use a SUBSTR(), and continue using REPLACE() to remove it from the middle of the list.

UPDATE
  table
SET images = 
  CASE
    /* if 3 is in the leftmost position in the list, remove first 2 chars... */
    WHEN LEFT(images, 2) = '3,' THEN SUBSTR(images, 3)
    /* if 3 is in the rightmost position in the list, remove last 2 chars... */
    WHEN RIGHT(images, 2) = ',3' THEN SUBSTR(images, 1, LENGTH(images) - 2)
    /* Otherwise replace a single 3 bounded by commas with a single comma */
    ELSE REPLACE(images, ',3,', ',')
  END
WHERE id = '1'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.