簡體   English   中英

MySql:按特定條件排序2列

[英]MySql: Sort 2 columns by certain conditions

我有以下列的社區表,如下所示:

在此輸入圖像描述

我需要按照“ ftr_order ”和“ isFeatured ”列對表進行排序,以便按以下順序顯示數據:

ftr_order | isFeatured

   2      |   yes
   1      |   no
   2      |   no
   3      |   no
   4      |   no
   5      |   no
   6      |   no
   0      |   no
   NULL   |   no
   NULL   |   no
   NULL   |   no

ftr_order應按升序對數據進行排序。 0和NULL值應該位於表的底部。 我嘗試了以下查詢,這在一定程度上解決了它,但我需要設置優先級即

i) 第一優先級 :如果isFeatured 是,則將其顯示在頂部。

ii) 第二優先級 :按升序排序ftr_order

** 注意:如果ftr_order0NULL,則在底部顯示數據。

SELECT * FROM community ORDER BY if(ftr_order = 0 or ftr_order is null,1,0), ftr_order ASC, community_description ASC

這將顯示以下輸出:

在此輸入圖像描述

在這里你可以看到ftr_order已經正確排序但是這里缺少一件事, ID號7應該列在表的頂部,因為這行有列isFeatured ='yes'。 為了將此行置於頂部,我嘗試通過寫下查詢來解決此問題:

SELECT * FROM community ORDER BY if(ftr_order = 0 or ftr_order is null,1,0 or isFeatured='yes'), ftr_order ASC, community_description ASC

您可以看到生成了以下輸出,您還可以分析仍然存在的問題。 ID號7應該列在表的頂部,但是這里的ID號7列在表的底部。 因此我需要將它移到頂部。 請幫我解決這個問題。 提前致謝!

在此輸入圖像描述

SELECT * FROM community ORDER BY isfeatured desc,ftr_order ASC,community_description ASC

你可以嘗試這樣,如果isfeatured只有是/否使它變得簡單

最后我得到了回答我自己的問題,解決方案如下:

SELECT * from (SELECT * FROM `community` ORDER BY if( ftr_order =0 OR ftr_order IS NULL , 1, 0 ) , ftr_order ASC , community_description ASC) as community ORDER BY CASE WHEN isFeatured ='yes' then isFeatured END desc

以下輸出將生成:

在此輸入圖像描述

這里isFeatured ='yes'位於頂部,其余數據按ftr_order升序排序,其中NULL和0將在結尾處。

ftr_order | isFeatured

   2      |   yes
   1      |   no
   2      |   no
   3      |   no
   4      |   no
   5      |   no
   6      |   no
   0      |   no
   NULL   |   no
   NULL   |   no
   NULL   |   no

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM