MySQL sort after argument in IN()

前端 未结 4 1283
刺人心
刺人心 2020-12-07 03:55

I have string containing a lot of IDs corresponding to my database. Like:

1,2,3,4,5

I then do a mySQL query to select all those rows:

相关标签:
4条回答
  • 2020-12-07 04:16

    you want the find_in_set function

    $list = "1,2,....";
    $sql = "select * from table where id in($list) order by find_in_set($id, '$list')";
    

    another (probably faster) option is to do sorting in php:

    $list = array(2, 3, ...);
    $s    = implode(',', $list);
    $sth  = mysql_query("select * from table where id in($s)");
    
    $rows = array();
    while($r = mysql_fetch_object($sth))
        $rows[$r->id] = $r;
    
    $sorted_rows = array();
    foreach($list as $id)
       $sorted_rows[] = $rows[$id];
    
    0 讨论(0)
  • 2020-12-07 04:17

    You might use order by with case ... end, though part between case and end should be generated by PHP:

    select
        *    
    from
        table
    where
        id in (2, 1, 3, 4, 5)
    order by
        case id
            when 2 then 1
            when 1 then 2
            when 3 then 3
            when 4 then 4
            when 5 then 5
        end asc
    
    0 讨论(0)
  • 2020-12-07 04:21

    You should be able to do this via the FIELD() function like so:

    SELECT * FROM `table` WHERE `id` IN (2,1,3,4,5) ORDER BY FIELD(`id`, 2,1,3,4,5) DESC
    

    That is:

    SELECT
      *
    FROM
      `table`
    WHERE
      `id` IN (".$myIDs.")
    ORDER BY
      FIELD(`id`, ".$myIDs.") DESC
    

    More in this blog post: Sorting MySQL rows using column values.

    0 讨论(0)
  • 2020-12-07 04:25

    Another option, though FIELD is probably the way to go in your case:

    SELECT * FROM `table` WHERE `id` IN (2,1,3,4,5) ORDER BY `id` = 2 DESC, `id` = 1 DESC,`id` = 3 DESC, `id` = 4 DESC, `id` = 5 DESC
    
    0 讨论(0)
提交回复
热议问题