為 MySQL 選擇查詢自定義 order by (Customize order by for MySQL select query)


問題描述

為 MySQL 選擇查詢自定義 order by (Customize order by for MySQL select query)

I want to do something like this: select * from table order by id asc with the exception that if the id is 5 (for example) make it be top, basically 5 then all other IDs ordered asc.

How can I do this please?

Thank you.


參考解法

方法 1:

You can also use function FIELD():

SELECT *
FROM table
ORDER BY FIELD(id, 5) DESC
       , id ASC

Especially useful if you want to have first the rows with say, id = 5, 23, 17, you can use:

SELECT *
FROM table
ORDER BY FIELD(id, 17, 23, 5) DESC
       , id ASC

方法 2:

You can use UNION as initally suggested by me, with a sorting on both columns as suggested by @Mike in the comments.

(SELECT *, 1 single_id FROM table_name WHERE id = 5)
UNION ALL
(SELECT *, 2 all_ids FROM table_name WHERE id <> 5)
ORDER BY single_id, id

Or better off with an IF statement, to avoid the overhead of two sorts:

  SELECT *, IF(id = 5, -1, id) ordering 
    FROM table_name
ORDER BY ordering ASC

方法 3:

SELECT *, CASE WHEN id = 5 THEN -1 ELSE id END AS ordering 
FROM table 
ORDER BY ordering ASC

方法 4:

SELECT * FROM table_name ORDER BY id=7 DESC, id ASC

Since this doesn't use indexes, I don't recommend using it on large tables.

(by FranciscypercubeᵀᴹShefdevinKaivosukeltaja)

參考文件

  1. Customize order by for MySQL select query (CC BY-SA 3.0/4.0)

#sql-order-by #SQL #MySQL






相關問題

如果提到,按特定值自定義 SQL 記錄集順序 (Customize SQL recordset order by specific value (s) if mentioned)

SQL Server 中的 OrderBy 將正值放在負值之前 (OrderBy in SQL Server to put positive values before negative values)

Đếm từ hai bảng và sắp xếp nó theo số lượng SQL tồn tại (Count from two tables and sort it out by the number of exist SQL)

按組中的最大值排序 (Order by the max value in the group)

.net中的SQLite中不區分大小寫的順序 (case insensitive order by in SQLite in .net)

MySQL:對 GROUP_CONCAT 值進行排序 (MySQL: Sort GROUP_CONCAT values)

為 MySQL 選擇查詢自定義 order by (Customize order by for MySQL select query)

如何從 MySQL 表中檢索 10 個最新的 DISTINCT IP? (How to retrieve 10 latest DISTINCT IP's from a MySQL table?)

按存儲在文本列中的日期排序表 (Order table by date stored in text column)

如何在 JavaScript 中對對象集合進行自然排序? (How to natural-sort a collection of objects in JavaScript?)

在 Postgres 中通過 json 數組(存儲為 jsonb)中的鍵對錶進行排序 (Order a table by a key in an array of json (stored as jsonb) in Postgres)

添加 row_number() 時 Oracle 值發生變化 (Oracle values change when row_number() added)







留言討論