我有一个用于搜索数据库的查询。查询以代码构建,术语参数化,因此一切运行良好且安全。我这样说是因为这些术语不能来自表格,因为它们是根据搜索字段中的用户输入生成的。
一切都像它应该的那样,我只是想知道是否有更好/更快的方式来执行搜索。
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上。
答案 0 :(得分:0)
您的查询对我来说足够好了。但是,如果您愿意通过为UNION
的每个部分重复连接条件来交换性能的可读性,那么您可以获得更好的执行计划:
....
INNER JOIN
(
SELECT id, 'title' TYPE, title SEARCH FROM article
where title like '%a railway employee%' or
title like '%railway employee%'
or title like '%a railway%'
or title like '%employee%'
or title like '%railway%'
or title like '%a%'
UNION ALL ....