MySQL - 如何在一列句子中搜索精确的单词匹配?

时间:2017-03-31 12:39:00

标签: mysql search

我有一个MySQL表,其中包含以下句子列表:

id | Sentence 
---+---------------------------------------------------------------
 1 | Come On Boys, You Can do it my boy.
 2 | Everything is possible, impossible itself says I am possible.
 3 | Boys I know possible solutions are good!
 4 | Possible solutions are all failed its also possible

我必须在Sentence列上搜索与possible相同的字词。

有一些条件:

  1. 搜索单词不能是任何单词的前缀或后缀。

    • 搜索字possibleimpossible不正确。
  2. 标点符号可以在单词之前或之后.Ex:!boyboy,

  3. possible Possible没有区分大小写的方法是正确的。
  4. 我尝试查询但是无效

    mysql_query("SELECT * FROM products WHERE Sentence LIKE '%".$search."%'");
    

    可能的标点符号为,.!?;-

    我需要一个有效的解决方案。提前致谢 !

3 个答案:

答案 0 :(得分:2)

您可以使用SELECT * FROM products WHERE Sentence REGEXP '[[:<:]]possible[[:>:]]' -- ^^^ ^^^ word boundaries

possible

这将对应于由单词边界包围的匹配REGEXP。在演示中请注意,标点符号计为单词边界。

另请注意,MySQL的possible不区分大小写,因此上述内容应与PossibleSub Replace_From_List() Dim cell As Range, rngFind As Range, counter As Long Dim RefSheet As String Dim ReplaceSheet As String Dim s As String RefSheet = "2052 Simplified Chinese" ReplaceSheet = "Translate" 'List of items to search for from Translated phases sheet column A With Sheets(RefSheet) Set rngFind = .Range("A1", .Range("A" & Rows.Count).End(xlUp)) End With For Each cell In rngFind 'Search in Sheet containing phases to translate Column A Set found = Sheets(ReplaceSheet).Range("A:A").Find(What:=cell.Value, _ LookIn:=xlValues, _ LookAt:=xlWhole, _ SearchOrder:=xlByRows, _ MatchCase:=False) If Not found Is Nothing Then 'When a match is found, replace Sheet "Translate" column B with Sheet "2052 Simplified Chinese" Column B 'Overwrites formulas s = found.Address Do found.Offset(, 1).Value = cell.Offset(, 1).Value counter = counter + 1 Set found = Sheets(ReplaceSheet).Range("A:A").FindNext(found) Loop While found.Address <> s End If Next cell MsgBox "Replacements made: " & counter, , "Replacements Complete" End Sub 匹配。

在这里演示:

Rextester

答案 1 :(得分:2)

使用REGEXP

SELECT *
FROM products
WHERE Sentence REGEXP '[^\\d\\w]possible[^\\d\\w]'

这会将每个单词possible包围在任何单词或数字中。

注意区分大小写。

答案 2 :(得分:1)

CREATE TEMPORARY TABLE tmp (id INTEGER PRIMARY KEY AUTO_INCREMENT, sentence VARCHAR(200));

INSERT INTO tmp (sentence) VALUES ('Come On Boys, You Can do it my boy.');
INSERT INTO tmp (sentence) VALUES ('Everything is possible, impossible itself says I am possible.');
INSERT INTO tmp (sentence) VALUES ('Boys I know possible solutions are good!');
INSERT INTO tmp (sentence) VALUES ('Possible solutions are all failed its also possible');

SELECT * FROM tmp WHERE sentence REGEXP '[[:<:]]impossible[[:>:]]';

这是重复的:Search for "whole word match" in MySQL