MySQL reverse order without DESC

前端 未结 2 388
有刺的猬
有刺的猬 2020-12-10 17:33

SELECT id FROM table LIMIT 8, 3

results in 8,9,10

but I need 10,9,8

How can you do this? If you add \"ORDER BY id DESC\" it gets 3,2,1

相关标签:
2条回答
  • 2020-12-10 18:04

    First of all, if you're not ordering at all, that you got 8,9,10 right now might be related to the index used. Are you sure this isn't going to change in the future?

    What I'm getting at is that unless you specify an order, you should not rely on it being the one you want.

    So I would definitely add an order to that select to specify what you want. Otherwise you're only saying "give me 3 numbers from this table", not "give me 3 numbers from this table according to these rules". Why is 3,2,1 wrong but 8,9,10 right? You're not specifying.

    Anyway, to answer your question, you must order after the limit, which means a subselect:

    SELECT id FROM (
        SELECT id FROM table LIMIT 8, 3
    ) AS dummy ORDER BY id DESC
    

    However, I would try this SQL instead, related to the part about specifying:

    SELECT id FROM (
        SELECT id FROM table ORDER BY id LIMIT 8, 3
    ) AS dummy ORDER BY id DESC
    
    0 讨论(0)
  • 2020-12-10 18:05

    Put your query in a subselect and then reverse the order in the outer select:

    SELECT id from (
        SELECT id FROM table ORDER BY id LIMIT 8, 3
    ) AS T1 ORDER BY id DESC
    

    Test data:

    CREATE TABLE table1 (id INT NOT NULL);
    INSERT INTO table1 (id) VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11);
    
    SELECT id from (
        SELECT id FROM table1 ORDER BY id LIMIT 8, 3
    ) AS T1 ORDER BY id DESC
    

    Result:

    10
    9
    8
    

    Note that the ORDER BY in the subquery is required otherwise the order is undefined. Thanks to Lasse for pointing this out!

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