Py学习  »  DATABASE

按外键排序mysql同一表

Sabra • 4 年前 • 151 次点击  

我有一个表(表顺序),具有索引到同一个表的外键,每个订单都有许多其他订单:

 order             
 ---------- 
 id_order
 state
 id_source

ID_source是同一表中ID_顺序的外键引用

我试过这个代码,但它没有给我想要的。

  select * from order o left join order o2 ON(o.id_order = o2.id_source)
  order by o.state , o2.state asc ; 

例如:

 id_order  |   state  |   id_source 
 -----------------------------------
     1     |     1    |     null
 -----------------------------------
     2     |     2    |     null  
 -----------------------------------
     3     |     3    |     null
 -----------------------------------
     4     |     1     |    3

我想要的结果

   id_order  |   state  |   id_source 
 -----------------------------------
     1       |     1    |     null
 -----------------------------------
     3       |     3    |     null
 -----------------------------------
     4       |     1    |    3
 -----------------------------------
     2       |     2    |     null  
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/38665
 
151 次点击  
文章 [ 1 ]  |  最新文章 4 年前
Matt Jameson
Reply   •   1 楼
Matt Jameson    5 年前

如果我对您的理解正确,那么您希望对ORDER BY使用一个条件语句,可以使用以下语句:

select * 
from order o 
left join order o2 ON(o.id_order = o2.id_source)
order by if(id_source is null, o.state, o2.state) asc;