简体   繁体   中英

How can I retrieve all 3rd level child nodes for all records in my table using SQL?

I have a table like so:

item(id, parent_id, data)

There are multiple data sets in the table. Each data set has a root record where parent_id is set to -1 . Any children of the parent record have their parent_id record set to the id of the parent. Any subsequent children have their parent_id set to that of their immediate parent.

Say I want to get all root nodes. That's easy

select * from item where parent_id = -1

Selecting all non-parent nodes is easy too:

select * from item where parent_id != -1

Question

How can I select only 3rd level nodes (from all records)? In my specific case I am trying to find is if there are any 3rd level nodes in my table, or alternatively get an affirmation that all of the non-root records in the table are 2nd level nodes.

Bonus Question (after working with Tom's answer)

This query returns 50,003 records:

SELECT
    count(L1.id)
FROM
    Item L1
WHERE
    L1.parent_id != -1;

This one returns 50,000 records:

SELECT
    count(L2.id)
FROM
    Item L1
INNER JOIN Item L2 ON L2.parent_id = L1.id
WHERE
    L1.parent_id = -1;

How do I isolate those 3 records to see what's going on with them?

Note

Bonus - turns out those 3 records were orphaned, not connected to a parent.

Since you're only going to three levels and exactly three levels, you can simply JOIN down to that level:

SELECT
    L3.id,
    L3.parent_id,
    L3.data
FROM
    Item L1
INNER JOIN Item L2 ON L2.parent_id = L1.id
INNER JOIN Item L3 ON L3.parent_id = L2.id
WHERE
    L1.parent_id = -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM