aryaxt
aryaxt

Reputation: 77626

Database - Writing a complex query?

I have a table that contains my node data in a tree view. Each node has it's own child. Is it possible to write a single statement to get each node along with it's children (each level sorted by a date), and their child for as many levels as exists?

- A
- B
-     F
-          L
-     G
- C
-     K
- D
-     H
-     I
-     J
- E

So the sql should return Each node has a parentId, when the parentId is null it means the node is a top level node

- A
- B
- F
- L
- G
- C
- K
- D
- H
- I
- J
- E

EDIT: Here is my table structure, and it's on a sqlite file. I really don't care about the version or RDBMS as long as I get the correct solution I'll convert it myself to sqlite and I'll get it to work

Node Table
___________________
int       - nodeId
int       - parentId /*referes to nodeId of the parent*/
varchar   - title
TimeStamp - dateCreate

Upvotes: 0

Views: 99

Answers (1)

user330315
user330315

Reputation:

As you say you don't care about the DBMS (even though you use SQLite):

This is the oracle solution:

SELECT lpad(' ',3*level)||title as title
FROM   your_table
CONNECT BY PRIOR nodeId = parentId
START WITH parentId IS NULL

This is the standard ANSI SQL Solution:

WITH RECURSIVE CatCTE (title, nodeId, parentId, lvl) as 
(
  SELECT title, nodeId, parentId, 1 as lvl
  FROM your_table
  WHERE parentId IS NULL

  UNION ALL

  SELECT c2.title, c2.nodeId, c2.parentId, CatCTE.lvl + 1
  FROM your_table c2 
    INNER JOIN CatCTE ON CatCTE.nodeId = c2.parentId
)
SELECT lpad(' ',3*level)||title as title
FROM CatCTE

(The only non-standard construct in there is the lpad function which is highly DBMS specific).

But I don't think you'll be able to "convert" either solution to SQlite

Upvotes: 3

Related Questions