SQL查询首先显示最新值,然后显示其他ASC

时间:2018-04-26 08:08:19

标签: sql sorting

我有一个新闻表,然后我使用foreach循环回显到一个滑块。 我需要调整查询的排序顺序,因此最后添加的(max id)总是先显示,其他的按id ASC排序。

例如:新闻1,2,3,4。我需要它们像4,1,2,3一样回应。

SELECT * FROM news ORDER BY sort ASC

如何首先以max(id)的形式添加另一个条件然后对ASC进行排序?

感谢。

2 个答案:

答案 0 :(得分:3)

您可以尝试此查询:

SELECT *
FROM (
   SELECT *,
         (SELECT MAX(Id) FROM news) AS max_id 
   FROM news) AS t
ORDER BY CASE WHEN id = max_id THEN 0 ELSE 1 END asc,
         id ASC

或使用CROSS JOIN

SELECT n.*
FROM news AS n
CROSS JOIN (SELECT MAX(Id) AS max_id FROM news) AS m
ORDER BY CASE WHEN n.id = m.max_id THEN 0 ELSE 1 END asc,
         n.id ASC

答案 1 :(得分:0)

或使用窗口功能

SELECT *
FROM (
    SELECT *, ROW_NUMBER() OVER (ORDER BY id DESC) AS RN
    FROM news) AS T
ORDER BY CASE WHEN RN = 1 THEN 0 ELSE 1 END, id

SELECT *
FROM (
    SELECT *, MAX(id) OVER () AS MaxID
    FROM news) AS T
ORDER BY CASE WHEN MaxID = id THEN 0 ELSE 1 END, id