搜索多个值 - SQL

时间:2012-01-24 19:37:25

标签: mysql sql

这是一次搜索多个值的最有效方法吗?

SELECT *
  FROM `table`
 WHERE (    (title LIKE %search term 1%)
         OR (description LIKE %search term 1%)
         OR (title LIKE %search term 2%)
         OR (description LIKE %search term 2%)
         OR (title LIKE %search term 3%)
         OR (description LIKE %search term 3%)
         OR (title LIKE %search term 4%)
         OR (description LIKE %search term 4%)
         OR (title LIKE %search term 5%)
         OR (description LIKE %search term 5%)
       )
;

2 个答案:

答案 0 :(得分:1)

如果您确实需要查找titledescription包含任何搜索字词的所有记录,那么该查询与您可以执行的操作一样好(1)重构您的架构,例如添加table_search_terms表,列table_idsearch_term(以便您可以编写SELECT table.* FROM table JOIN table_search_terms on table.id = table_search_terms.table_id WHERE search_term = 'search term 1' OR ...),或者(2)安装专用工具进行全文搜索索引(例如Lucene的)。任何较小的更改,例如使用INSTRREGEXP而不是LIKE,可能会略微提高查询速度(或者可能会略微减慢速度),但不会产生非常明显的影响。< / p>

答案 1 :(得分:1)

看起来你可能想要查看全文搜索:

http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

您的查询如下:

SELECT * FROM table 
WHERE MATCH (title,description)
AGAINST ('"search term 1" "search term 2" "search term 3" "search term 4" "search term 5"' IN BOOLEAN MODE);

您需要在桌面上定义全文索引,但几乎在所有情况下都会比原始查询更快。