gpt4 book ai didi

mysql在单列中搜索多个子字符串

转载 作者:行者123 更新时间:2023-11-29 04:42:10 24 4
gpt4 key购买 nike

我需要一种有效的方法来搜索表的同一列中的多个子字符串。以下是我创建的示例表和低效查询。谁能帮我让它更有活力。

id | column_2 | column_2
1 | 65,35 | 14,13,20
2 | 41,15,16 | 10,21,23
3 | 12,14,15 | 10,12,20

SELECT * FROM `table1` WHERE `column_2` LIKE '%10%' AND `column_2` LIKE '%23%';

这些值会很长,并且条件的数量也是动态的。那么是否有任何有效的方法来创建删除和条件(具有)的查询。

最佳答案

我从这里获取函数 SPLIT_STR:MYSQL - Array data type, split string,

我们的数据集

假设我们有以下数据集;

select * from a_table;
+----+-------------+
| id | column2 |
+----+-------------+
| 1 | 10,11,23 |
| 2 | 5,14,23 |
| 3 | 2,18 |
| 4 | 23,10,11 |
| 5 | 230,100,110 |
| 6 | 11,100 |
+----+-------------+
6 rows in set

函数

然后我们创建函数(上面引用);

CREATE FUNCTION SPLIT_STR(
x VARCHAR(255),
delim VARCHAR(12),
pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
delim, '');

最终查询

从那里,我们可以做一个简单的查询;

SELECT id from a_table WHERE SPLIT_STR(column2, ",", 1) IN (10,23)

这将给出以下结果集;

SELECT id from a_table WHERE SPLIT_STR(column2, ",", 1) IN(10,23);
+----+
| id |
+----+
| 1 |
| 4 |
+----+
2 rows in set

添加更多号码

要添加更多数字,只需添加到 IN() 函数 - 逗号分隔值。

备注

深思this

Don't store comma separated values in a single column. The problem you have with the query stems directly from that bad design choice. – a_horse_with_no_name

关于mysql在单列中搜索多个子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26196359/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com