社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

按外键排序mysql同一表

Sabra • 5 年前 • 171 次点击  

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

 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
 
171 次点击  
文章 [ 1 ]  |  最新文章 5 年前
Matt Jameson
Reply   •   1 楼
Matt Jameson    6 年前

如果我对您的理解正确,那么您希望对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;