这是一次搜索多个值的最有效方法吗?
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%)
)
;
答案 0 :(得分:1)
如果您确实需要查找title
或description
包含任何搜索字词的所有记录,那么该查询与您可以执行的操作一样好(1)重构您的架构,例如添加table_search_terms
表,列table_id
和search_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的)。任何较小的更改,例如使用INSTR
或REGEXP
而不是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);
您需要在桌面上定义全文索引,但几乎在所有情况下都会比原始查询更快。