简体   繁体   English

MySQL regexp对一组术语

[英]MySQL regexp against an array of terms

I have the following query which searches a column for a given string 我有以下查询在列中搜索给定的字符串

SELECT * FROM table WHERE column_name REGEXP '$search_term'

Is it possible to search that column to see whether it contains one (or more) words from an array? 是否可以搜索该列以查看它是否包含数组中的一个(或多个)单词?

you can use FIND_IN_SET() to find one or more words 您可以使用FIND_IN_SET()来查找一个或多个单词

SELECT * 
FROM table 
WHERE FIND_IN_SET(column_name, 'word1,word2,word3')

what find in set does is it looks at the value inside a column and compares it to the values in your comma separated string. 在set中查找的内容是查看列中的值并将其与逗号分隔字符串中的值进行比较。

CAUTION!!!!! 警告!!!!!

don't put a variable directly in a query like that.. it makes you VULNERABLE to SQL INJECTION attacks!!!! 不要将变量直接放在这样的查询中......它会使你对SQL INJECTION攻击产生破坏性! you should look into using prepared statements.. look HERE for help with sql injection 你应该研究一下使用预处理语句。看看这里有关sql注入的帮助

NOTE: 注意:

if you dont have a way to get a comma separated list of words you can use GROUP_CONCAT().. I'll provide a demo below using both ways. 如果你没有办法得到一个逗号分隔的单词列表,你可以使用GROUP_CONCAT()..我将使用两种方式提供下面的演示。

here is a SQLFIDDLE 这是一个SQLFIDDLE

QUERY: 查询:

SET @word_list := (SELECT GROUP_CONCAT(words) FROM test where id IN(1, 3, 4));

SELECT @word_list;

after assigning the string to @word_list you want to see whats in it so I select it. 在将字符串分配给@word_list之后,您想要查看其中的内容,以便我选择它。

OUTPUT: OUTPUT:

'whatever,maybe,final'

now lets run the find in set query with the user defined variable and then again with just the string. 现在让我们使用用户定义的变量在set query中运行find,然后再使用字符串再次运行find。

QUERY: 查询:

SELECT * 
FROM test 
WHERE FIND_IN_SET(words, @word_list );

OUTPUT: OUTPUT:

+----+----------+
| id | words    |
+----+----------+
| 1  | whatever |
| 3  | maybe    |
| 4  | final    |
+----+----------+

WRITING IT IN: 写下来:

SELECT * 
FROM test 
WHERE FIND_IN_SET(words, 'whatever,maybe,final')

OUTPUT: OUTPUT:

+----+----------+
| id | words    |
+----+----------+
| 1  | whatever |
| 3  | maybe    |
| 4  | final    |
+----+----------+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM