我的网站上有一个搜索表单,允许用户搜索公司的员工。我正在使用输入来搜索mySql DB中的表。我的SELECT状态在这里:
SELECT title, uid FROM table_data
WHERE title LIKE '%$search_name%' AND blog_id = 6
ORDER BY title ASC LIMIT 50
目前,搜索“Jon”会产生一些像:
Angela Jones
Dejonas Lucero
Ernesto Jon
Jon White
Rick Jonston
有没有办法让它按此顺序排序?
search_name%
%search_name
%search_name%
Jon White
Ernesto Jon
Angela Jones
Dejonas Lucero
Rick Jonston
答案 0 :(得分:6)
这是一种方法,虽然我觉得它不是很优雅:
SELECT title, uid FROM table_data
WHERE title LIKE '%$search_name%' AND blog_id = 6
ORDER BY IF( title LIKE '$search_name%',0,
IF( title LIKE '%$search_name', 1, 2 ) )
限制50
如果匹配'search_name%',则为每个标题指定一个'0',如果匹配'%search_name',则指定1,否则指定2'(根据WHERE子句为'%search_name%')。
然后按它排序(升序)。
您也可以使用CASE WHEN..THEN..END
声明执行此操作:
SELECT title, uid FROM table_data
WHERE title LIKE '%$search_name%' AND blog_id = 6
ORDER BY CASE WHEN title LIKE '$search_name%' THEN 0
WHEN title LIKE '%$search_name' THEN 1
ELSE 2
END
答案 1 :(得分:0)
您需要发出三个单独的查询并连接结果集。您可以在一个查询中执行以下操作:
SELECT '1' as q, title, ... WHERE title LIKE '$search_name%' ...
UNION
SELECT '2' as q, title, ... WHERE title LIKE '%$search_name' ...
UNION
SELECT '3' as q, title, ... WHERE title LIKE '%$search_name%' ...
ORDER BY 1,2