从 SET 字段中删除值的最佳方法? [英] The best way to remove value from SET field?

查看:32
本文介绍了从 SET 字段中删除值的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新 mysql SET 字段的最佳方法是从字段中删除特定值.

Which is the best way to update a mysql SET field, to remove a specific value from the field.

例如.具有值的字段类别:1、2、3、4、5?我想从列表中删除2":

Eg. field categories with values: 1,2,3,4,5? I want to remove '2' from the list:

UPDATE table 
SET categories = REPLACE(categories, ',2,', ',') 
WHERE field LIKE '%,2,%';

但是如果 '2' 是列表中的第一个或最后一个值呢?

But what if '2' is the first or the last value from the list?

UPDATE table 
SET categories = REPLACE(categories, '2,', '') 
WHERE field LIKE '2,%';

UPDATE table 
SET categories = REPLACE(categories, ',2', '') 
WHERE field LIKE ',2%';

如何用一个查询处理所有 3 个案例?!

How could I handle all 3 cases with one single query?!

推荐答案

如果你需要从集合中移除的值不能多次出现,你可以使用这个:

If the value you need to remove from the set can't be present more than once, you could use this:

UPDATE yourtable
SET
  categories =
    TRIM(BOTH ',' FROM REPLACE(CONCAT(',', categories, ','), ',2,', ','))
WHERE
  FIND_IN_SET('2', categories)

看到它在这里工作.如果该值可以多次出现,这将删除它的所有出现:

see it working here. If the value can be present more than once, this will remove all occourences of it:

UPDATE yourtable
SET
  categories =
    TRIM(BOTH ',' FROM
      REPLACE(
        REPLACE(CONCAT(',',REPLACE(col, ',', ',,'), ','),',2,', ''), ',,', ',')
    )
WHERE
  FIND_IN_SET('2', categories)

这篇关于从 SET 字段中删除值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆