The best way to remove value from SET field?(从 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 字段中删除值的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 SET 字段中删除值的最佳方法?


- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- SQL 临时表问题 2022-01-01