I have community table with following columns as shown below:
I need to sort table by " ftr_order " and " isFeatured " columns in a certain way that it displays data in the following order:
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 should sort data in ascending order. 0 and NULL values should come at the bottom of the table. I have tried the following query, this resolved it to some extent, but I need to set priority ie
i) First Priority : If isFeatured is yes then show it on the top.
ii) Second Priority : Sort ftr_order in ascending order
** Note: If ftr_order is 0 or NULL then display data at bottom.
SELECT * FROM community ORDER BY if(ftr_order = 0 or ftr_order is null,1,0), ftr_order ASC, community_description ASC
This displays the following output:
Here you can see that ftr_order has been sorted out correctly but one thing is missing here, ID number 7 should be listed on the top of the table as this row has column isFeatured ='yes'. In order to bring this row on the top I tried to resolve it by writing down the query:
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
You can see the following output is generated and you can also analyze what issue is still left. ID number 7 should be listed on the top of the table, but here ID number 7 is listed at the bottom of the table. Therefore I need to shift it on the top. Please help me out to resolve this issue. Thanks in advance!
SELECT * FROM community ORDER BY isfeatured desc, ftr_order ASC, community_description ASC
You can try like this if isfeatured has only yes/no make it simple
Finally I got answer to my own question, solution is as follows:
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
Following output will be generated:
Here isFeatured ='yes' is at the top and rest of the data is order by ftr_order ascending where NULL and 0 will come at the end.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.