开发者

Like and equal SQL order by equal?

Say I have the following table:

ID      Author
---------------------
1       Bill
2       Joe
3       Bill and Joe
4       Bill

And I want a result set that would come from:

SELECT id FROM table WHERE Author LIKE '%Bill%' OR Author = 'Bill'

How could I order it so that the rows matched with e开发者_高级运维quality are the first rows returned and the like matches comes after? e.g. The query would return 1,4,3. I am using MySQL but would take answers in any DB.


SELECT  id
FROM    YourTable
WHERE  Author LIKE '%Bill%' 
ORDER BY CASE WHEN Author = 'Bill' THEN 0
              ELSE 1
         END 

You can probably just do ORDER BY Author != 'Bill' as well - Not sure about ordering by boolean expressions in MySQL.


SELECT id 
FROM table 
WHERE Author LIKE '%Bill%'
order by if(author='Bill',1,2)


If that test needs to be expanded to several variables, I have expanded a bit Martin's answer in the following manner (for instance on 3 criteria):

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) 

Best regards (and many thanks to Martin),


I have tested your data in db and ORDER BY works as you wish without any problems but you can use the following query:

New query:

select Author, CONCAT(Author, ' ') as text_n 
from table where Author like '%Bill%' order by text_n;

Your edited query:

SELECT id FROM table WHERE Author LIKE '%Bill%' order by Author;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜