mysql IN的问题

mysql in 的排序

select id from table where id in (2,1,36);
查出来的结果是:1 2 3 6
但是有的时候是要:2 1 3 6

有2种方法:

1. select id from table where id in (2,1,3,6) order by substring_index('2,1,3,6',id,1);

substring_index(str,delim,count) 字符串截取函数
str 要截取的字符串 delim 截取的分割符 count 截取的数量
返回从字符串str的第count个出现的分隔符delim之后的子串。如果count是正数,返回最后的分隔符到左边(从左边数) 的所有字符。如果count是负数,返回最后的分隔符到右边的所有字符(从右边数)。
那 order by substring_index(‘2,1,3,6′,id,1) 这个啥意思呢
这个是在字符串’2,1,3,6′里查找id,如果找不到,就返回整个字符串。

2.select id from table where id in (2,1,3,6) order by find_inset(id,'2,1,3,6')

find_in_set(str,strlist) 字符串函数
如果字符串str在由N子串组成的表strlist之中,返回一个1到N的值。如果str不是在strlist里面或如果strlist是空字符串,返回0。

mysql> SELECT FIND_IN_SET('b','a,b,d,e');
        -> 2

所以 find_in_set返回的是一个1到N的值,在order by的话,就是按顺序排了。

你可能感兴趣的:(mysql)