Mysql remove the specific word in comma seperated string

后端 未结 6 795
温柔的废话
温柔的废话 2020-12-20 03:35

My table had \'tags\' field like this:

Tags

tag1,tag2,tag3

How to remove \',tag2\' including comma using mysql query.

6条回答
  •  庸人自扰
    2020-12-20 03:57

    Apart from the first answer which I didn't test and therefore I have no opinion about, the others would fail in the below cases:

    1- tags = "tag1,tag2,tag22,tag3"
    2- tags = "tag2,tag1,tag3"
    

    in the first example, the REPLACE(tags, 'tag2', '') function will remove the third comma separted value i.e. tag22 as well, and in the second example tag2 will not be replaced by REPLACE(tags, ',tag2', '')

    one possible solution can be:

    REPLACE(REPLACE(CONCAT(',', tags, ','), 'tag2', ''), ',,', ',')
    

    the problem with my solution is that you will always ending up with having values stores with redundant commas both at the start and the end of string. but in my case it works well.

提交回复
热议问题