SQLize Online / PHPize Online  /  SQLtest Online

A A A
Share      Blog   Popular
Copy Format Clear
CREATE TABLE TBL (NodeKey INT, ParentKey INT, Child CHAR, Parent CHAR); INSERT INTO TBL VALUES (1, NULL, 'A', NULL),(2, NULL, 'B', NULL),(3, NULL, 'C', 'A'),(4, NULL, 'C', 'B'),(5, NULL, 'D', 'C'); SELECT * FROM TBL; SELECT TBL.NodeKey, PK AS ParentKey, TBL.Child, TBL.Parent FROM TBL LEFT JOIN ( SELECT Child, MIN(NodeKey) PK FROM TBL GROUP BY Child ) P ON P.Child = TBL.Parent; SELECT TBL.NodeKey, MIN(P.NodeKey) AS ParentKey, TBL.Child, TBL.Parent FROM TBL LEFT JOIN TBL P ON P.Child = TBL.Parent GROUP BY TBL.NodeKey, TBL.Child, TBL.Parent;
Stuck with a problem? Got Error? Ask ChatGPT!
Copy Clear