[英]How do I sort MySQL search results be relevance?
I'm using PDO to search a MySQL table for search results. 我正在使用PDO在MySQL表中搜索搜索结果。 My query looks like this
我的查询看起来像这样
$sql = "SELECT * FROM users WHERE username LIKE :username OR name LIKE :name ORDER BY uniqueid DESC LIMIT 6";
$stmt = $conn->prepare($sql);
$stmt->bindValue(':username', '%'.$query.'%');
$stmt->bindValue(':name', $query.'%');
What I'm trying to accomplish is that in my results array, the results that match like this: 我要完成的是在我的results数组中,匹配的结果如下:
$query.'%'
Should appear before results that match like this: 应该出现在符合以下条件的结果之前:
'%'.$query.'%'
Is there a way to sort results by such relevance without two queries, preferably in pure SQL? 有没有一种方法可以按这种相关性对结果进行排序,而无需两个查询,最好是在纯SQL中?
You could order the results by the index of $query
in username
and name
: 您可以按
username
和name
中$query
的索引对结果进行排序:
SELECT * FROM users
WHERE username LIKE :username OR name LIKE :name
ORDER BY uniqueid DESC, INSTR(:query, username), INSTR(:query, name) LIMIT 6
Note, however, that ordering by results of a function requires full table scan in MySQL. 但是请注意,按函数结果排序需要在MySQL中进行全表扫描。
您可以轻松使用以下查询:
$SQL = "SELECT * FROM users WHERE username LIKE :username OR name LIKE :name ORDER BY name LIKE :name DESC, uniqueid DESC LIMIT 6"; –
Well, Eugene's answer seems the most appropriate in this case. 好吧,在这种情况下,尤金的答案似乎是最合适的。 Provided below is an alternate solution to the problem in general which allows further customizations in terms of sorting the result :
下面提供的是一般问题的替代解决方案,它允许在排序结果方面进行进一步的自定义:
If you have data like this : 如果您有这样的数据:
Id Name
1 Aabbee
2 Aabriella
3 Aada
4 bahlelah
5 cailelah
6 daielah
7 gaisha
8 Aisha
9 Aishath
10 dalelh
11 Eleasha
Then, you can use the following query: 然后,您可以使用以下查询:
select '1' as Relevance,ID, Name from MyTable where Name like 'el%' /*The results with the priority (or relevance) should be first */
union
select '2' as Relevance,ID, Name from MyTable where Name like '%el%' and Name not like 'el%' /* The lower priority results go here*/
order by Relevance
This will result in: 这将导致:
Relevance ID Name
1 11 Eleasha
2 2 Aabriella
2 4 bahlelah
2 5 cailelah
2 6 daielah
2 10 dalelh
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.