对数据进行排序MySQL的

问题描述:

我有一个表是这样的:对数据进行排序MySQL的

 
id  content parent_id 
265 flower NULL  
266 shroom NULL  
267 ccccccc NULL  
268 ddddddd NULL  
275 b1  266 
276 b2  266 
277 sub text 275 

,我想这样的输出:

 
id  content parent_id 
265 flower NULL  
266 shroom NULL 
275 b1  266 
277 sub text 275 
276 b2  266  
267 ccccccc NULL  
268 ddddddd NULL  

在口头上:由空排序它,如果它已得到PARENT_ID我想把它放在DESC命令下面。

我已经试过类似:

SELECT * 
FROM notes 
ORDER BY if (parent_id is not null, parent_id, id) id 

sqlfiddle:http://www.sqlfiddle.com/#!2/0418a7/1/0

+1

您的预期输出似乎按内容而不是parent_id排序。 – NavkarJ

+0

按内容排序...或按parent_id排序asc – scaisEdge

+0

我不想按内容排序。 –

我没有测试过这一点。尽管如此,尝试沿着这些路线。

select id, content, parent_id 
    from notes 
order by coalesce(parent_id, id); 

这仍然会造成孩子在父母面前出现(很少但可能)的情况。