首先,我需要获得完全匹配,如
SELECT * FROM movies WHERE title='STRING' ORDER BY x DESC
然后使用LIKE match
追加到这些结果查询SELECT * FROM movies WHERE title LIKE '%STRING&' AND title<>'STRING' ORDER BY x DESC
并以最多10个结果限制这些结果。
UNION不会做这些工作,因为它将所有结果排序在一起并返回错误的顺序(我需要先完全匹配,然后再用LIKE)
SELECT * FROM movies WHERE title='STRING' UNION
SELECT * FROM movies WHERE title LIKE '%STRING%' ORDER BY x DESC LIMIT 10
我得到的最佳解决方案是使用multi_query()
$query = "SELECT * FROM movies WHERE title='STRING' ORDER BY x DESC; ";
$query .= "SELECT * FROM movies WHERE title LIKE '%STRING%' AND title<>'red' ORDER BY x DESC";
$Dbi->multi_query($query);
do {
$sql = $Dbi->store_result();
while($x = $sql->fetch_array()) {
...
}
} while($Dbi->next_result());
但是在这种情况下,不可能在内部循环中使用任何mysql,并且还必须有更好看的解决方案!
答案 0 :(得分:2)
您可以使用order by
子句通过一个查询执行此操作:
SELECT *
FROM movies
WHERE title like '%STRING%'
ORDER BY title = 'STRING' desc,
title like '%STRING%' desc
LIMIT 10;
ORDER BY
中的第一个子句首先放置完全匹配。然后第二个按部分匹配排序。 WHERE
子句确保存在某种匹配。
答案 1 :(得分:1)
你不需要UNION,它两次访问同一个表:
SELECT *
FROM movies
WHERE title LIKE '%STRING&'
ORDER BY CASE WHEN title='STRING' THEN 1 ELSE 2 END
LIMIT 10
答案 2 :(得分:0)
(SELECT * FROM movies WHERE title='STRING')
UNION
(SELECT * FROM movies WHERE title LIKE '%STRING%' ORDER BY x DESC LIMIT 10)