说我有下表:
ID Author
---------------------
1 Bill
2 Joe
3 Bill and Joe
4 Bill
我想要一个来自的结果集:
SELECT id FROM table WHERE Author LIKE '%Bill%' OR Author = 'Bill'
我如何订购它以便与相等匹配的行是返回的第一行,之后是匹配的?例如查询将返回1,4,3
。我正在使用MySQL,但会在任何数据库中获取答案。
答案 0 :(得分:8)
SELECT id
FROM YourTable
WHERE Author LIKE '%Bill%'
ORDER BY CASE WHEN Author = 'Bill' THEN 0
ELSE 1
END
你也可以只做ORDER BY Author != 'Bill'
- 不确定在MySQL中按布尔表达式排序。
答案 1 :(得分:2)
SELECT id
FROM table
WHERE Author LIKE '%Bill%'
order by if(author='Bill',1,2)
答案 2 :(得分:0)
如果该测试需要扩展到几个变量,我已按以下方式扩展了一点Martin的答案(例如,基于3个标准):
SELECT id
FROM YourTable
WHERE Author LIKE '%Bill%'
ORDER BY
(CASE WHEN criteria_1='target_1' THEN 1 ELSE 2 END)
*
(CASE WHEN criteria_2='target_2' THEN 1 ELSE 2 END)
*
(CASE WHEN criteria_3='target_3' THEN 1 ELSE 2 END)
致以最诚挚的问候(非常感谢Martin),
答案 3 :(得分:-1)
我已经在db和ORDER BY中测试了您的数据,没有任何问题,但您可以使用以下查询:
新查询:
select Author, CONCAT(Author, ' ') as text_n
from table where Author like '%Bill%' order by text_n;
您编辑的查询:
SELECT id FROM table WHERE Author LIKE '%Bill%' order by Author;