我有一个用于搜索数据库的查询。查询在代码中构建,并且术语被参数化,因此一切运行良好且安全。我这么说是因为这些术语不能来自表格,因为它们是根据搜索字段的用户输入生成的。
一切正常,我只是想知道是否有更好/更快的方式来执行搜索。
SELECT
sum(score * multiplier) score,
a.id,
a.title
FROM
(
SELECT 3 score, 'a railway employee' term UNION ALL
SELECT 2 score, 'railway employee' term UNION ALL
SELECT 2 score, 'a railway' term UNION ALL
SELECT 1 score, 'employee' term UNION ALL
SELECT 1 score, 'railway' term UNION ALL
SELECT 0 score, 'a' term
) terms
CROSS JOIN
(
SELECT 'title' TYPE, 1 multiplier
UNION ALL SELECT 'summary', 1.1
UNION ALL SELECT 'detail', 1.5
) X
INNER JOIN
(
SELECT id, 'title' TYPE, title SEARCH FROM article
UNION ALL
SELECT id, 'summary' TYPE, summary SEARCH FROM article WHERE summary <> ''
UNION ALL
SELECT artId, 'detail' TYPE, txt SEARCH FROM articleSections
) s ON s.TYPE = x.TYPE AND SEARCH LIKE concat('%', terms.term, '%')
INNER JOIN article a ON a.id = s.id
GROUP BY id, title
ORDER BY score DESC;
;
sqlfiddle上有一个功能简单的演示。