【发布时间】:2016-03-02 01:04:19
【问题描述】:
我正在尝试在下表中编写一个 sql 查询。
╔════╦══════════╦═══════╗======╗======╗
║ ID ║ NAME ║ CLASS ║PARENT║ DOB ║
╠════╬══════════╬═══════╣======║======║
║ 1 ║ DAVID ║ SPIN ║ ║1 ║
║ 2 ║ AROON ║ BIKE ║ 1 ║1 ║
║ 3 ║ LEO ║ YOGA ║ ║2 ║
║ 4 ║ LIN ║ CYC ║ 1 ║2 ║
║ 5 ║ STEFA ║ YOGA ║ ║3 ║
║ 6 ║ GLORIA ║ RUNN ║ 1 ║3 ║
╚════╩══════════╩═══════╝======╝======╝
并且,该表的输出应该如下所示
╔════╦════════╦═══════╗======╗======╗
║ ID ║ NAME ║ CLASS ║PARENT║ DOB ║
╠════╬════════╬═══════╣======║======║
║ 1 ║ DAVID ║ SPIN ║ ║1 ║
║ 2 ║ AROON ║ BIKE ║ 1 ║1 ║
║ 4 ║ LIN ║ CYC ║ 1 ║2 ║
║ 6 ║ GLORIA║ RUNN ║ 1 ║3 ║
║ 3 ║ LEO ║ YOGA ║ ║2 ║
║ 5 ║ STEFAN║ YOGA ║ ║3 ║
╚════╩════════╩═══════╝======╝======╝
So this is the explanation of the output
First parent David as his DOB is 1,
--David three childrens sorted based on DOB
Then LEO as his DOB is 2
-- Leo do not have children[if he did, would be here as sorted on DOB]
Then Stefan as his DOB is 3
-- Stefan do not have children [if he did, would be here as sorted on DOB]
那么我尝试了什么?
SELECT * FROM user group by ID, PARENT ;
在 SQL 之上,语句返回父子组中的项目但不保持任何顺序,当我添加 ORDER BY、SQL 时,似乎不再尊重 GROUP BY。
然后我尝试加入并以两张完全不同的表结束,其中一张包含所有父母,另一张包含所有孩子。 UNION ALL 在这两个查询上返回了预期的数据集,但不是按预期的顺序。
有什么想法吗?
更新
Output should be
Pick entry [based on min time ].
--use that id and find all of its children and placed them in sorted order
repeat for every row in the table
注意:
--parents are sorted based on DOB
--child's are also sorted based on DOB
--DOB are valid timestamp
--PARENT, ID field both are UUID and define as CHAR, PARENT reference to ID
更新 1
以下查询
WITH RECURSIVE
top AS (
SELECT * FROM (SELECT * FROM user WHERE PARENT is null ORDER BY dob LIMIT 1)
UNION
SELECT user.NAME, user.PARENT, user.ID, user.CLASS, user.DOB FROM user, top WHERE user.PARENT=top.ID
ORDER BY user.dob
) SELECT * FROM top;
返回以下输出:
╔════╦════════╦═══════╗======╗======╗
║ ID ║ NAME ║ CLASS ║PARENT║ DOB ║
╠════╬════════╬═══════╣======║======║
║ 1 ║ DAVID ║ SPIN ║ ║1 ║
║ 2 ║ AROON ║ BIKE ║ 1 ║1 ║
║ 4 ║ LIN ║ CYC ║ 1 ║2 ║
║ 5 ║ GLORIA║ RUNN ║ 1 ║3 ║
╚════╩════════╩═══════╝======╝======╝
输出对第一个父母有好处。但是,仍然无法弄清楚,我怎样才能按排序顺序遍历其余的父母和他们的孩子。
【问题讨论】:
-
输出看起来与输入相同。这是怎么回事?
-
不只是重新检查的 put 与 put 不同。
-
我看到的唯一区别是排序。我也不喜欢使用
SELECT *和GROUP BY。 -
是的,你是对的,这里有两种不同的顺序。没有孩子的条目被排序,孩子也被排序,因为它们被放置在自己的父母之后。
-
我真的不明白你想在输出中显示什么。此外,在 id 列上进行分组没有任何意义 - 大概所有 id 都是唯一的,因此没有什么可分组的。