MySQL - 从字符串中搜索确切的单词

时间:2017-02-04 05:45:00

标签: mysql

我想从字符串中搜索确切的单词,如

id  Description
1   This is nice pen looking good
2   This is nice pendrive looking good

搜索字符串pen

我当前的查询

SELECT * FROM `table` WHERE Description like '%pen%';

以上查询返回两个记录,但我想只有第一个记录。因为字与我的搜索字符串完全匹配。

预期输出

1   This is nice pen looking good

Demo

4 个答案:

答案 0 :(得分:3)

尝试使用正则表达式:

SELECT 
    *
FROM
    `table`
WHERE
    Description regexp '(^|[[:space:]])pen([[:space:]]|$)';

Demo

或使用word boundaries

SELECT 
    *
FROM
    `table`
WHERE
    Description regexp '[[:<:]]pen[[:>:]]';

答案 1 :(得分:2)

您可以使用REGEXP以及[[:<:]][[:>:]]字边界标记:

SELECT
    *
FROM
    `table`
WHERE
    Description REGEXP '[[:<:]]pen[[:>:]]';

SQL Fiddle Demo

答案 2 :(得分:0)

您可以使用全文匹配,如下所示

Request failed: Could not load file or assembly 'PerformanceTestingUtilities, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

您也可以选择布尔模式,它会在搜索结果中返回准确的单词

答案 3 :(得分:0)

尝试此操作以获得确切的单词结果

apply