zoukankan      html  css  js  c++  java
  • select in 查询结果无顺序及解决办法

    现有如下mysql表:

    mysql> select * from in_demo;
    +----+-----+
    | id | num |
    +----+-----+
    |  1 |   8 |
    |  2 |   7 |
    |  3 |   6 |
    +----+-----+
    3 rows in set

    按如下sql查询结果如下:

    mysql> SELECT * FROM in_demo WHERE num in (6,7,8);
    +----+-----+
    | id | num |
    +----+-----+
    |  1 |   8 |
    |  2 |   7 |
    |  3 |   6 |
    +----+-----+
    3 rows in set

    可以看出并没有按照in中的6,7,8进行排序,而是按照主键id进行排序。那如何做到按照in中的字段进行排序呢

    mysql> SELECT * FROM in_demo WHERE num in (6,7,8) ORDER BY FIND_IN_SET(num,'6,7,8');
    +----+-----+
    | id | num |
    +----+-----+
    |  3 |   6 |
    |  2 |   7 |
    |  1 |   8 |
    +----+-----+
    3 rows in set

    其中find_in_set(str1,str2)函数是返回str2中str1所在的位置索引,ORDER BY FIND_IN_SET(num,'6,7,8')  相当于按照num在6,7,8中的顺序排序,所以也就能按in中的顺序进行排序了。

  • 相关阅读:
    MessageFormat理解,MessageFormat.format(Object obj)方法
    正则表达式
    数字处理类
    包装类
    遍历Map的4种方法(来自网络)
    集合类
    数组
    字符串
    语言基础
    Linux下使用openssl加解密
  • 原文地址:https://www.cnblogs.com/silenceshining/p/15579657.html
Copyright © 2011-2022 走看看