To add a comma separated value, there are no duplicates in mysql update Query

I store table data as comma separated values ​​such as

id    name       fk_id

1      abc       2,4,6
2       def      2,7,8

Now I want to use CASE WHEN or some function in Update Query of MySQL that updates a field if it does not have a duplicate value:

For example, the same value for fk_id then ignores another update, for example, if 10 for id 1 is then updated, but if 7 for id 2, then ignore

id    name       fk_id

1      abc       2,4,6,10
2       def      2,7,8

I tried the following code:

if(
            find_in_set($fk_id,fk_id),
            fk_id, 
            CONCAT_WS(',', fk_id, $fk_id)
          )

But does not work.

+4
source share
2 answers

Just update your code as

set fk_id = if(find_in_set($fk_id,fk_id),
            fk_id, 
            CONCAT(fk_id, ',', $fk_id)
          )
+2
source

Try the following:

$sql = "
UPDATE `test` 
SET `fk_id` = CONCAT(fk_id, ',','" . $fk_id . "') 
WHERE `fk_id` REGEXP ',?(" . $fk_id . "),?'
";

NOTE. REGEXP is not the best option when it comes to speed.

0

Source: https://habr.com/ru/post/1628073/


All Articles