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,970
  • 10
  • 45
  • 59
Mik
  • 105
  • 1
  • 10

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,242,037
  • 58
  • 646
  • 786
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,780
  • 4
  • 27
  • 37