简体   繁体   中英

How do I sort the result of this MySQL query as I want them?

Here's the data I have;

type      valid blocked
--------- ----- --------
CPI       0     0
CPI       1     0
CPI       0     1
CPI       1     1
CPA       0     0
CPA       1     0
CPA       0     1
CPA       1     1
CPE       0     0
CPE       1     0
CPE       0     1
CPE       1     1
PIN       0     0
PIN       1     0
PIN       0     1
PIN       1     1

Here's how I want it sorted;

type      valid blocked
--------- ----- --------
CPI       1     0
CPA       1     0
CPI       1     1
CPA       1     1
CPI       0     0
CPA       0     0
CPI       0     1
CPA       0     1
CPE       1     0
CPE       1     1
CPE       0     0
CPE       0     1
PIN       1     0
PIN       1     1
PIN       0     0
PIN       0     1

So, CPI and CPA first, sorted by valid then unblocked. Next its CPI sorted by valid then unblocked and finally PIN, again sorted by valid and unblocked.

Is that even possible to sort like this in one query? Thanks.

select * from your_table
order by case when type in ('CPI','CPA') then 1
              when type = 'CPE' then 2
              when type = 'PIN' then 3
         end,
         valid <> 0, 
         blocked
select * from your_table
order by `type` in ('CPI','CPA') desc
    , `type` = 'CPE' desc
    , `type` = 'PIN' desc
    , valid desc, blocked
    , `type` = 'CPI' desc
;

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM