0

Those are the cases on table column post_attending, post_attending could be: 5 or 5,6,7 or 6,7,5 or 6,5,7 or '' or longer string comma separated and 5 on this or not. How should I do to delete "5" and "possible" , surrounding it using in PDO query?

I tried this:

$q= "UPDATE table SET post_attending = SUBSTR(REPLACE(CONCAT(',', post_attending, ','), ? , ','), 2, LENGTH(REPLACE(CONCAT(',', post_attending, ','), ? , ',')) - 2) WHERE id = x "
$sql->execute(array(5,5,x)); 

but it leaves me a , when there is a 5 or 5 is at the end.

I have read this also TRIM(BOTH ',' FROM REPLACE(wishes, '(,)? :var (,)?', '')) don't really figured out the right syntax.

andr
  • 15,640
  • 10
  • 42
  • 56
Mik
  • 105
  • 1
  • 9

2 Answers2

0

Try this:

update table
    set post_attending = (case when val like '5,%' then SUBSTRING(val, 3, LENgth(val) - 2)
                               when val like '%,5' then SUBSTRING(val, 1, length(val) - 2)
                               when val = '5' then ''
                               else REPLACE(val, ',5,', ',')
                           end)
Gordon Linoff
  • 1,198,228
  • 53
  • 572
  • 709
0

without using any CASE statement, and I believe it would be faster

UPDATE table SET post_attending = SELECT REPLACE(REPLACE(REPLACE(REPLACE(val, ',5,', ','), ',5', ''), '5,', ''),'5', '')
vikas
  • 2,612
  • 4
  • 24
  • 34