php 以相反的顺序“按降序排序”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3647063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:33:25  来源:igfitidea点击:

"Order by desc" in reverse order?

phpsqlmysqlsql-order-by

提问by marc

Welcome,

欢迎,

I'm wondering is it possible to reverse returned data in sorting "order by desc" but i want that data in reverse order.

我想知道是否可以在“按降序排序”排序时反转返回的数据,但我希望该数据以相反的顺序排列。

For example, i got table with values

例如,我得到了带有值的表

ID
1
2
3
4

And i do

我做

Order by ID ASC LIMIT 3 I got

按 ID 排序 ASC LIMIT 3 我得到了

1
2
3

When i do Order by ID DESC limit 3 i get

当我按 ID DESC 限制 3 订购时,我得到

4
3
2

I would like to have

我想拥有

3
2
1

So i would like to order by ASC but revers results. I was always doing this in PHP side using array_reverse, but today i want ask You. Maybye i'm wrong and i can do this just in Mysql. Regards

所以我想按 ASC 订购,但结果相反。我一直在 PHP 端使用 array_reverse 这样做,但今天我想问你。Maybye 我错了,我只能在 Mysql 中做到这一点。问候

回答by Mchl

SELECT * 
FROM (
  SELECT ... 
  FROM ... 
  ORDER BY ID ASC 
  LIMIT 3
) AS sq 
ORDER BY ID DESC

Think of it as working in two steps. First it executes the inner query: selects 3 records with lowest IDs. Then in the outer query it sorts them in descending order.

把它想象成分两步工作。首先它执行内部查询:选择 3 个具有最低 ID 的记录。然后在外部查询中,它按降序对它们进行排序。

回答by Mark Byers

You can fetch the first three rows using a subquery and then reverse the order of these rows in an outer query:

您可以使用子查询获取前三行,然后在外部查询中颠倒这些行的顺序:

SELECT *
FROM
(
    SELECT *
    FROM yourtable
    ORDER BY ID
    LIMIT 3
) T1
ORDER BY ID DESC

回答by Your Common Sense

Nope, you aren't wrong. There are no difference for any sensible amount of data. Array_reverse is all right.
That's not a thing you have to be concerned too much of. Just use whatever you like more - for readability or other subjective reasons

不,你没有错。任何合理的数据量都没有区别。Array_reverse 没问题。
这不是你需要过多担心的事情。只需使用您更喜欢的任何东西 - 出于可读性或其他主观原因

回答by Colin Hebert

You can do this with a sub query :

您可以使用子查询执行此操作:

SELECT * FROM
    (SELECT * FROM myTable ORDER BY idMyTable LIMIT 0, 3) AS r
ORDER BY r.idMyTable DESC


Resources :

资源 :

回答by Gumbo

You could use an outer SELECTto reverse the order:

您可以使用外部SELECT来反转顺序:

SELECT *
FROM (
    SELECT …
    ORDER BY id ASC
    LIMIT 3
) sub
ORDER BY id DESC