选择包含子字符串的 MySQL 字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18809976/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 18:51:03  来源:igfitidea点击:

SELECT MySQL field that contains a substring

mysqlsqlstring

提问by A. K. M. Tariqul Islam

Using LIKE is very common in MySQL. We use it like this: WHERE field LIKE '%substring%'. Where we have a substring and field has full string. But what I need is something opposite. I have substrings in field. So, I want that row which contains a substring of my string. Suppose the table is:

使用 LIKE 在 MySQL 中很常见。我们用这样的:WHERE field LIKE '%substring%'。我们有一个子字符串,字段有完整的字符串。但我需要的是相反的东西。我在字段中有子字符串。所以,我想要包含我的字符串的子字符串的那一行。假设表是:

----+-------------------
 id | keyword
----+-------------------
  1 | admission
----+-------------------
  2 | head of the dept
----+-------------------

and I have a string from user: Tell me about admission info. I need such a MySQL query that returns admissionas this is a substring of user string. Something like:

我有来自用户的字符串:Tell me about admission info。我需要这样一个 MySQL 查询,它返回,admission因为这是用户字符串的子字符串。就像是:

SELECT keyword FROM table WHERE (keyword is a substring of 'Tell me about admission info')

thanks in advance.

提前致谢。

回答by Adriaan Stander

You re looking for the LIKEoperator

您正在寻找LIKE运算符

Pattern matching using SQL simple regular expression comparison. Returns 1 (TRUE) or 0 (FALSE). If either expr or pat is NULL, the result is NULL.

模式匹配使用 SQL 简单正则表达式比较。返回 1 (TRUE) 或 0 (FALSE)。如果 expr 或 pat 为 NULL,则结果为 NULL。

Something like

就像是

SELECT  keyword 
FROM    table 
WHERE   ('Tell me about admission info' LIKE CONCAT('%', keyword, '%'))

SQL Fiddle DEMO

SQL小提琴演示

回答by F. Hauri

This work fine, using REGEXP:

这工作正常,使用REGEXP

SELECT  keyword 
FROM    table 
WHERE   'Tell me about admission info' REGEXP keyword;

But this work only if keyworddon't contain Regular expression's escapes...

但这项工作只有在keyword不包含正则表达式的转义...

I.e. This will work fine while keywordcontain only letters, numbers, spaces and so on.

即这将工作正常,同时keyword只包含字母、数字、空格等。

回答by 7alhashmi

Try something like this:

尝试这样的事情:

SELECT CASE WHEN 'Tell me about admission info' 
   LIKE CONCAT('%',`keyword`,'%')
   THEN `keyword` else null END as `keyword`

FROM    table1

WHERE CASE WHEN 'Tell me about admission info' 
  LIKE CONCAT('%',`keyword`,'%')
  THEN `keyword` else null END is not null;

SQL Fiddle..

SQL小提琴..