1

I've a MySQL database in which there is a table named customers. Inside this table there is a field named preferences, which content is a list of names, single or composite.

Table customers:

id   name   preferences
---------------------------------
1    John   pears,tomato sauce,bread
2    Rose   carrot cake, salad

I can easily add an new entry in the field preferences doing something like:

UPDATE `customers` 
  SET preferences = CONCAT(preferences,',oranges') 
WHERE id=2

But now, I wonder if there is an easy way to remove a known item in that list, which does not mean, read back the registry entry, processing it using PHP and saving it again.

I was trying to use REGEX_REPLACE unsuccessfully, since the word can be at the beginning, middle or end. So I didn't succeed to write a proper expression for substituting the results. Anyway Regular expressions, is probably not the right way to go.

Thanks

Carles
  • 418
  • 2
  • 18

1 Answers1

1

Try this:

Update `customers`
    set preferences = TRIM(BOTH ',' FROM TRIM(BOTH 'oranges' FROM TRIM(REPLACE(CONCAT(" "',oranges'" "),' ,oranges ',''))));

It will delete ',oranges'. If there is no space before and after ,oranges it would not delete it. As you can see it is not a Regex anymore. Also TRIM(BOTH 'oranges' will delete 'oranges' from first and last place in the string.

DEMO

Andrei Suvorkov
  • 5,559
  • 5
  • 22
  • 48