我想在波纹管表上写一个SQL查询。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
在这两个查询返回预期的数据集,但不是按预期的顺序。
有什么想法?
UPDATE
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 ║
╚════╩════════╩═══════╝======╝======╝
输出是良好的第一个亲本。但是,仍然无法弄清楚,我如何通过排序顺序遍历其余的父母和他们的孩子。
输出看起来与输入相同。这里发生了什么? –
不只是检查出来放在不同的地方。 – minhaz
我看到的唯一区别是排序。我也不会为使用'GROUP BY'使用'SELECT *'而疯狂。 –