我想在波紋管表上寫一個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 *'而瘋狂。 –