【MySQL】透過 FIELD 函式自訂排序


Posted by Jianna on 2021-09-21

在實作會員權限管理的過程中,一直在思考如何可以優化得更好。
想著想著,發現能從成員的顯示順序開始做起。原先沒有在語法中下 ORDER BY,是依照預設,也就是寫入資料庫的順序去撈資料。

我想著,比較直觀的做法應該是讓管理員顯示於最上方,停權者顯示於最下方。可是我在資料庫的設計上,在權限這個欄位所使用的分別是:0->停權者、1->管理員、99->一般成員。若是依照一些常用的方法(ASC、DESC)去排序,似乎無法達到我要的效果。於是在一番搜索後,萬能的估狗大神又告訴了我答案。

這邊使用的是 FIELD(str, str1, str2, str3,...),說明如下:

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

該函式會回傳指定字串在字串序列中的位置,若將回傳結果用來排序,恰好能達成我所想要的效果。

ORDER BY FIELD(role, 1, 99, 0)

登登!如此一來就大功告成啦~
不過也有爬到文說這樣做的效能並不太好,不過目前資料蠻輕量的,就先這樣做做看。
若在排序種類多的情況下,建議還是多開一張表去記錄各個類別的順序。

參考資料:
MySQL 的自訂排序
How to define a custom ORDER BY order in mySQL


#MySQL #Custom Sorting







Related Posts

Return the summation of the number smaller than n

Return the summation of the number smaller than n

Test

Test

React(3) - class component & state

React(3) - class component & state


Comments