复杂的mysql搜索查询,'boolean和'在mysql字符串上搜索关键字

时间:2013-06-28 17:14:27

标签: mysql

我需要在我的应用程序上实现一些搜索参数,并且无法提出任何更好的解决方案,所以我希望你们能帮助我,我的问题就像这样 - >

我有一个包含以下列的表格,
编号,问题

现在我应该搜索具有各种标准的关键字,例如 - >

  1. 如果我搜索关键词“心脏病”,则返回的问题应包含单词“heart”和“disease”
  2. 因为“心脏”包含“心脏”所以返回像“我们有一个心脏病”的句子,但是因为“foo”在“心脏”之前并且不是因为“我们有一个fooheart病”所以不返回根据给出的标准是不可接受的。但任何追随“心脏”或“疾病”的事物都是可以接受的。
  3. 这些是给出的标准,我知道我的英语不是那么令人印象深刻,也无法正确解释我的问题。但我希望有一个解决方案!谢谢!

1 个答案:

答案 0 :(得分:1)

你可能会更喜欢像Lucene这样的全文搜索引擎,但是你可以在mysql中做到这一点。您只需要根据单词数量建立搜索条件。在许多情况下,这将是一个非常低效的查询。

类似

select * from table
 where text like '% heart%' and text like '% disease%' 

Link to SQLFiddle

应该有用。

请注意,这不一定是完整的解决方案。不会返回以下值,因为疾病或心脏之前不会有空间。

Diseases are bad.Hearts are very susceptible.  

问题当然是你必须开始构建很多特殊情况。为了解决这些评论以及我展示的示例,您必须添加以下规则:

select * from terms
 where (terms like '% heart%' or terms like 'heart%' or terms like '%.Heart%')
     and (terms like '% disease%' or terms like 'disease%' or terms like '%.disease%')

Link to more advanced case

您也可以使用某种正则表达式执行此操作。这将处理你提出的案件。

select * from terms
 where (terms like 'heart%' or terms REGEXP '[ |\.]heart')
  and (terms like 'disease%' or terms  REGEXP '[ |\.]disease')

Example with regular expressions