![](/img/trans.png)
[英]MySQL - Sort certain conditions last in the result set (Unions maybe?)
[英]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_order为0或NULL,则在底部显示数据。
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.