Returning query results in predefined order

前端 未结 11 1008
温柔的废话
温柔的废话 2020-11-29 06:01

Is it possible to do a SELECT statement with a predetermined order, ie. selecting IDs 7,2,5,9 and 8 and returning them in that order, based on

相关标签:
11条回答
  • 2020-11-29 06:31

    It's hacky (and probably slow), but you can get the effect with UNION ALL:

    SELECT id FROM table WHERE id = 7
    UNION ALL SELECT id FROM table WHERE id = 2
    UNION ALL SELECT id FROM table WHERE id = 5
    UNION ALL SELECT id FROM table WHERE id = 9
    UNION ALL SELECT id FROM table WHERE id = 8;
    

    Edit: Other people mentioned the find_in_set function which is documented here.

    0 讨论(0)
  • 2020-11-29 06:35

    You may need to create a temp table with an autonumber field and insert into it in the desired order. Then sort on the new autonumber field.

    0 讨论(0)
  • 2020-11-29 06:35

    Erm, not really. Closest you can get is probably:

    SELECT * FROM table WHERE id IN (3, 2, 1, 4) ORDER BY id=4, id=1, id=2, id=3
    

    But you probably don't want that :)

    It's hard to give you any more specific advice without more information about what's in the tables.

    0 讨论(0)
  • 2020-11-29 06:36

    I didn't think this was possible, but found a blog entry here that seems to do the type of thing you're after:

    SELECT id FROM table WHERE id in (7,2,5,9,8) 
    ORDER BY FIND_IN_SET(id,"7,2,5,9,8");
    

    will give different results to

    SELECT id FROM table WHERE id in (7,2,5,9,8) 
    ORDER BY FIND_IN_SET(id,"8,2,5,9,7");
    

    FIND_IN_SET returns the position of id in the second argument given to it, so for the first case above, id of 7 is at position 1 in the set, 2 at 2 and so on - mysql internally works out something like

    id | FIND_IN_SET
    ---|-----------
    7  | 1
    2  | 2
    5  | 3
    

    then orders by the results of FIND_IN_SET.

    0 讨论(0)
  • 2020-11-29 06:37

    You get answers fast around here, don't you…

    The reason I'm asking this is that it's the only way I can think of to avoid sorting a complex multidimensional array. I'm not saying it would be difficult to sort, but if there were a simpler way to do it with straight sql, then why not.

    0 讨论(0)
  • 2020-11-29 06:37

    One Oracle solution is:

    SELECT id FROM table WHERE id in (7,2,5,9,8)
    ORDER BY DECODE(id,7,1,2,2,5,3,9,4,8,5,6);
    

    This assigns an order number to each ID. Works OK for a small set of values.

    0 讨论(0)
提交回复
热议问题