您的位置:首页 > 数据库 > MySQL

mysql id in 排列问题

2012-06-04 10:30 344 查看
mysql id in 排列问题
SELECT * FROM szmg0112.cms_archives c where id in(13934,13914,13915,13923,13910,13891,13920,13882,13937,13924,13881) order by substring_index('13934,13914,13915,13923,13910,13891,13920,13882,13937,13924,13881',id,1)

语句可以根据id里面的顺序来排列查询。

select id from table where id in (2,1,3,5) order by field(id,2,1,3,5)

mysql in 默认的排序

select id from table where id in (2,1,3,5);

查出来的结果是:1 2 3 5

但是有的时候是要:2 1 3 5

这就需要做排序的时候做处理,网上有2种方法,但是没有详细的解释。查了下手册,记下方便自己以后查找。
select id
from table
where id in
(2,1,3,5)
order by
substring_index('2,1,3,5',id,1);

substring_index(str,delim,count) 字符串截取函数

str 要截取的字符串 delim 截取的分割符 count 截取的数量

返回从字符串str的第count个出现的分隔符delim之后的子串。如果count是正数,返回最后的分隔符到左边(从左边数) 的所有字符。如果count是负数,返回最后的分隔符到右边的所有字符(从右边数)。

那 order by substring_index(‘2,1,3,5′,id,1) 这个啥意思呢

这个是在字符串’2,1,3,5′里查找id,如果找不到,就返回整个字符串

select id from table where id in (2,1,3,5) order by find_inset(id,'2,1,3,5')
find_in_set(str,strlist)
字符串函数
如果字符串str在由N子串组成的表strlist之中,返回一个1到N的值。如果str不是在strlist里面或如果strlist是空字符串,返回0。

SELECT FIND_IN_SET('b','a,b,c,d');
-> 2
所以 find_in_set返回的是一个1到N的值,在order by的话,就是按顺序排了。


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  mysql table c