---
title: "MySql查询结果按照指定顺序排序"
author: "164418960"
date: "2015-01-20T14:31:24Z"
tags: ["MySQL"]
categories: ["数据库"]
slug: "mysql"
draft: false
lastmod: "2015-01-20T14:31:24Z"
id: 2177652
url: "https://164418960.iteye.com/blog/2177652"
---

Mysql这功能做的很好用啊！！

 

让查询结果按照指定顺序排序

\----------------------------------------------------------------------

表结构如下:  
mysql&gt; select * from test;  
+----+-------+  
| id | name  |  
+----+-------+  
|  1 | test1 |  
|  2 | test2 |  
|  3 | test3 |  
|  4 | test4 |  
|  5 | test5 |  
+----+-------+

执行以下SQL:  
mysql&gt; select * from test where id in(3,1,5);  
+----+-------+  
| id | name  |  
+----+-------+  
|  1 | test1 |  
|  3 | test3 |  
|  5 | test5 |  
+----+-------+  
3 rows in set (0.00 sec)

这个select在mysql中得结果会自动按照id升序排列,  
但是我想执行"select * from test where id in(3,1,5);"的结果按照in中得条件排序,即:3,1,5,想得到的结果如下:  
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);