2016-02-01 47 views
0

有3行是否有可能按SQLAlchemy中的優先級排序?

| Name | State | 
| 1 | Busy | 
| 2 | Online | 
| 3 | Offline | 

我想給優先 「在線」> 「忙」> 「離線」

heroes = HeroModel.query.\ 
      filter(HeroModel.id.in_(hero_ids)).\ 
      order_by(???????). \ 
      all() 

如何訂購?而不是按字母順序。

+1

你正在連接哪個數據庫? – Utsav

+0

你應該使用整數來表示狀態,然後順序很容易。 – doru

回答

0

使用這樣的事情在你的選擇查詢

case state 
when 'online' then 1 
when 'offline' then 2 
else 3 
end as rnk 

,並使用ORDER BY這一派生列rnk

order by rnk 
0

可以在SQLAlchemy中試試這個(如果你使用Oracle或MySQL):

heroes = HeroModel.query.\ 
      filter(HeroModel.id.in_(hero_ids)).\ 
      order_by(
      case(
       [(HeroModel.state == "online", 0), 
       (HeroModel.state == "busy", 1), 
       (HeroModel.state == "offline", 2)], 
       else_=3). \ 
     all()