0

首先我需要得到完全匹配

SELECT * FROM movies WHERE title='STRING' ORDER BY x DESC

然后使用 LIKE 匹配附加到这些结果查询

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 并且还必须有更好看的解决方案!

4

3 回答 3

2

order by您可以使用以下子句通过一个查询来执行此操作:

SELECT *
FROM movies 
WHERE title like '%STRING%'
ORDER BY title = 'STRING' desc,
         title like '%STRING%' desc
LIMIT 10;

中的第一个子句ORDER BY将完全匹配放在首位。然后第二个按部分匹配排序。该WHERE子句确保存在某种匹配。

于 2013-08-30T14:48:58.343 回答
1

您不需要 UNION,它访问同一个表两次:

SELECT *
FROM movies
WHERE title LIKE '%STRING&'
ORDER BY CASE WHEN title='STRING' THEN 1 ELSE 2 END
LIMIT 10
于 2013-08-30T14:54:49.413 回答
0
(SELECT * FROM movies WHERE title='STRING')
UNION
(SELECT * FROM movies WHERE title LIKE '%STRING%' ORDER BY x DESC LIMIT 10)
于 2013-08-30T14:51:17.607 回答