开发者

MySQL reverse order without DESC

开发者 https://www.devze.com 2022-12-20 22:32 出处:网络
SELECT id FROM table LIMIT 8, 3 results in 8,开发者_如何学Python9,10 but I need 10,9,8 How can you do this? If you add \"ORDER BY id DESC\" it gets 3,2,1 Put your query in a subselect and then reve

SELECT id FROM table LIMIT 8, 3

results in 8,开发者_如何学Python9,10

but I need 10,9,8

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


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!


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

精彩评论

暂无评论...
验证码 换一张
取 消