社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

检查MySQL Where子句中枚举列的逗号分隔字符串[重复]

B.Balamanigandan • 5 年前 • 1418 次点击  

我有一个用户表,其中包含一个列(比如interest),该列的值是以逗号分隔的interest id。 例如

user  interests
A     12,13,15
B     10,11,12,15
C     9,13
D     10,12

现在,我有一个用逗号分隔的值为“13,15”的字符串。

当我的表中有很多用户时,SQL会是什么呢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/55104
 
1418 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Community neuronaut
Reply   •   1 楼
Community neuronaut    7 年前

如果要基于松散匹配获取结果,则可以执行以下查询:

松散匹配意味着兴趣 135,151 在搜索“13,15”时也会出现。

SET @inputInterest := "13,15";

SELECT 
*
FROM userinterests
WHERE interests REGEXP REPLACE(@inputInterest,',','|');

对于给定的数据,您将得到如下输出:

| ID | user |   interests |
|----|------|-------------|
|  1 |    A |    12,13,15 |
|  2 |    B | 10,11,12,15 |
|  3 |    C |        9,13 |

SQL FIDDLE DEMO

编辑:

如果您希望得到基于至少一个兴趣的结果,那么您可以使用regex,正如@Andrew在这个答案中提到的那样:

以下是我根据他的见解修改了我的查询:

SET @inputInterest := "13,15";

SELECT 
*
FROM userinterests
WHERE interests REGEXP CONCAT('(^|,)(', REPLACE(@inputInterest, ',', '|'), ')(,|$)')

SEE DEMO OF IT

注:

你需要更换 @inputInterest

建议:

Is storing a delimited list in a database column really that bad?

Andrew
Reply   •   2 楼
Andrew    8 年前

它可以用regexp@1000111完成,但是使用更复杂的regexp。看看这个,例如:

(^|,)(13|15)(,|$)

1,13,2
13,1,2
1,13
13,2
13

但不符合这些

1,135,2
131,2
1,113

这是查询:

SET @search = '13,15';

SELECT *
FROM test
WHERE interests REGEXP CONCAT('(^|,)(', REPLACE(@search, ',', '|'), ')(,|$)')