我只是尝试对我的网站进行一些小搜索以查找用户条目并以逻辑方式对它们进行排序,我尝试改进结果,但最终得到了一个太大的查询字符串,需要14秒才能执行在我的服务器上。所以我现在想知道如何在不对结果进行任何更大改动的情况下优化查询。
这是我当前的查询:
$query = "SELECT * FROM(
SELECT 1 as m_rank,title,rank, content, url, keywords FROM websites
WHERE title LIKE '".$search."'
union all
SELECT 2 as m_rank,title,rank, content, url, keywords FROM websites
WHERE title LIKE '".$search."%'
OR title LIKE '%".$search."'
union all
SELECT 3 as m_rank,title,rank, content, url, keywords FROM websites
WHERE title LIKE '%".$search."%'
union all
SELECT 4 as m_rank,title,rank, content, url, keywords FROM websites
WHERE keywords LIKE '".$search."'
union all
SELECT 5 as m_rank,title,rank, content, url, keywords FROM websites
WHERE keywords LIKE '%".$search."'
OR keywords LIKE '".$search."%'
union all
SELECT 6 as m_rank,title,rank, content, url, keywords FROM websites
WHERE keywords LIKE '%".$search."%'
union all
SELECT 7 as m_rank,title,rank, content, url, keywords FROM websites
WHERE content LIKE '".$search."'
union all
SELECT 8 as m_rank,title,rank, content, url, keywords FROM websites
WHERE content LIKE '%".$search."'
OR content LIKE '".$search."%'
union all
SELECT 9 as m_rank,title,rank, content, url, keywords FROM websites
WHERE content LIKE '%".$search."%'
) a
ORDER BY m_rank, rank DESC LIMIT ".$page.", ".$max;
是否还可以使用PHP进行预处理来削减查询?
答案 0 :(得分:2)
您可以使用一个查询执行此操作。将不同的搜索条件放在case
中以指定m_rank
。类似的东西:
SELECT title, rank, content, url, keywords,
(case when title LIKE '".$search."' then 1
when title LIKE '".$search."%' OR title LIKE '%".$search."' then 2
when title LIKE '%".$search."%' then 3
. . .
else NULL
end) as m_rank
FROM websites
HAVING m_rank is not null
ORDER BY m_rank, rank DESC
LIMIT ".$page.", ".$max;