My table had 'tags' field like this:
Tags
tag1,tag2,tag3
How to remove ',tag2' including comma using mysql query.
My table had 'tags' field like this:
tag1,tag2,tag3
How to remove ',tag2' including comma using mysql query.
I think the best answer to such issue is on the below link The best way to remove value from SET field?
query should be like this which covers the ,value or value, or only value in the comma separated column
UPDATE yourtable SET categories = TRIM(BOTH ',' FROM REPLACE(CONCAT(',', col, ','), ',2,', ',')) WHERE FIND_IN_SET('2', categories)
Here you can have your condition in where clause. for more details refer above link.
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.
For a SET data type, you could use something like this -
CREATE TABLE sets(tags SET('tag1','tag2','tag3'));
INSERT INTO sets VALUES
('tag1,tag2'),
('tag1,tag3,tag2'),
('tag2,tag3'),
('tag3,tag1');
UPDATE sets SET tags = tags &~ (1 << FIND_IN_SET('tag2', tags) - 1);
SELECT * FROM sets;
+-----------+
| tags |
+-----------+
| tag1 |
| tag1,tag3 |
| tag3 |
| tag1,tag3 |
+-----------+
A quick tip:
UPDATE sets SET tags = tags &~ (1 << FIND_IN_SET('tag2', tags) - 1);
Does not work when your set looks like: 'tag1','tag2','tag3'
'tag3' will get lost by this operation
I ended up using a simple double replace:
UPDATE sets SET tags = replace(replace(tags, 'tag2', ''), ',,', '')
The wrapping replace removes left over comma's from replacing just 'tag2', as you can't be sure if your tagg will be the first or last item of the set
regarding the case of tag22 leaving a 2, doing it without leading zero's as the OP did, your bound for trouble anyway
Use replace function in MySQL:
replace(FIELD_NAME, ‘find this string’, ‘replacement string’);
so in your case:
SELECT REPLACE('tag1,tag2,tag3', ',tag2', '');
For more details look at: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace
I found a solution, but would love to know if there is an easier way of doing it... SELECT TRIM(BOTH ',' FROM (SELECT REPLACE(REPLACE('tag1,tag2,tag3','tag2',''),',,',',')))