Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何按父子顺序对SQL中的记录进行排序_Sql_Sorting_Columnsorting - Fatal编程技术网

如何按父子顺序对SQL中的记录进行排序

如何按父子顺序对SQL中的记录进行排序,sql,sorting,columnsorting,Sql,Sorting,Columnsorting,我有一个列为“ItemId”和“ParentItemId”的表。我希望结果按父子顺序排序。这样,就有其他列需要对数据进行排序。 我希望首先根据“itemType”对数据进行排序 例如 AutoId | itemId | parentItemId | itemType 1 1 0 3 2 2 null 4 3 3 0 6

我有一个列为“ItemId”和“ParentItemId”的表。我希望结果按父子顺序排序。这样,就有其他列需要对数据进行排序。 我希望首先根据“itemType”对数据进行排序

例如

 AutoId | itemId | parentItemId | itemType
   1        1       0               3
   2        2       null            4
   3        3       0               6
   4        4       null            5
   5        5        1              9
   6        6        2              9
   7        7        3              9
   8        8        4              9
   9        9        0              2
   10       10       0              1
现在,我希望结果以如下格式绘制

 AutoId | itemId | parentItemId | itemType
   10       10        0              1
   9        9         0              2
   1        1         0              3
   5        5         1              9
   2        2        null            4
   6        6         2              9
   4        4        null            5
   8        8         4              9
   3        3         0              6 
   7        7         3              9
有什么方法可以像这样对记录进行排序吗


任何帮助都将不胜感激。谢谢。

对于MySql,请将ifnull用于parentItemId字段 像

甲骨文

select *
from table
order by NVL(parentItemId, itemId), itemId
您可以这样做:

select *
from table1
order by coalesce(parentitemid,itemid), itemid

示例:

摘自@hkutluay answer for SQL Server:

按ISNULL(parentItemID,ItemID),ItemID从表1中选择*

这假设父母的
项目ID
总是小于孩子的
项目ID
,但这似乎是一个合理的假设。
select *
from table1
order by coalesce(parentitemid,itemid), itemid