MySQL查詢(xún)結(jié)果按某值排序
MySQL查詢(xún)結(jié)果如何排序呢?這是很多人都提過(guò)的問(wèn)題,下面就教您如何對(duì)MySQL查詢(xún)結(jié)果按某值排序,如果您感興趣的話(huà),不妨一看。
之前有一個(gè)功能修改,要求MySQL查詢(xún)結(jié)果中:
id name * * *
1 lucy ...
3 lucy ...
2 lily ...
4 lucy ...
名字為lucy的優(yōu)先排在前面,百思不得其解,可能有人會(huì)說(shuō)簡(jiǎn)單 union嘛 或者弄個(gè)臨時(shí)表什么的,其實(shí)我也想過(guò),但是本身SQL邏輯就很多了(上面只是簡(jiǎn)例),再u(mài)nion的話(huà)或者臨時(shí)表可能繞很大的彎路,后來(lái)看到一篇文章嘗試著加入order by find_in_set(name,'lucy') ,結(jié)果 得到的結(jié)果為lucy全部在下面,隨即我改為order by find_in_set(name,'lucy') desc 實(shí)現(xiàn)結(jié)果為
id name * * *
1 lucy ...
3 lucy ...
4 lucy ...
2 lily ...
基本實(shí)現(xiàn),可是又有點(diǎn)不確定的心情,查mysql文檔發(fā)現(xiàn)find_in_set語(yǔ)法
- FIND_IN_SET(str,strlist)
假如字符串str 在由N 子鏈組成的字符串列數(shù)據(jù)表strlist 中, 則返回值的范圍在 1 到 N 之間 。一個(gè)字符串列數(shù)據(jù)表就是一個(gè)由一些被『,』符號(hào)分開(kāi)的自鏈組成的字符串。如果***個(gè)參數(shù)是一個(gè)常數(shù)字符串,而第二個(gè)是type SET列,則 FIND_IN_SET() 函數(shù)被優(yōu)化,使用比特計(jì)算。如果str不在strlist 或strlist 為空字符串,則返回值為 0 。如任意一個(gè)參數(shù)為NULL,則返回值為 NULL。 這個(gè)函數(shù)在***個(gè)參數(shù)包含一個(gè)逗號(hào)(『,』)時(shí)將無(wú)法正常運(yùn)行
- mysql> SELECT FIND_IN_SET('b','a,b,c,d');
- -> 2
看了這個(gè)我估計(jì)結(jié)果為什么要加desc 了 find_in_set返回的值是,當(dāng)存在lucy的時(shí)候 返回他的位置,沒(méi)有的時(shí)候?yàn)?,空的時(shí)候null,所以排序?yàn)?,1,1,0,如果加在列上就為
id name FIND_IN_SET * *
1 lucy 1 ...
3 lucy 1 ...
2 lily 0 ...
4 lucy 1...
表結(jié)構(gòu)如下:
- mysql> select * from test;
- +----+-------+
- | id | name |
- +----+-------+
- | 1 | test1 |
- | 2 | test2 |
- | 3 | test3 |
- | 4 | test4 |
- | 5 | test5 |
- +----+-------+
執(zhí)行以下SQL:
- mysql> select * from test where id in(3,1,5);
- +----+-------+
- | id | name |
- +----+-------+
- | 1 | test1 |
- | 3 | test3 |
- | 5 | test5 |
- +----+-------+
- 3 rows in set (0.00 sec)
這個(gè)select在mysql中得結(jié)果會(huì)自動(dòng)按照id升序排列,
但是我想執(zhí)行"select * from test where id in(3,1,5);"的結(jié)果按照in中得條件排序,即:3,1,5,想得到的結(jié)果如下:
id name
3 test3
1 test1
5 test5
方法如下:
- select * from test where id in(3,1,5) order by find_in_set(id,'3,1,5');
- select * from test where id in(3,1,5) order by substring_index('3,1,2',id,1);
兩者均可
【編輯推薦】