简体   繁体   中英

SQL Queries on Table with “Forest” structure

I'm using MySQL 5.5 . Suppose I have an SQL table that has an "N-forest" structure as follows:

create table foo
(
    id int not null primary key,
    parent_id int,
    bar varchar(255),

    foreign key (parent_id) references foo (id)
)

If parent_id is null it signifies a root element. Also we guarantee it is acyclic.

I now want to select the row with id @x and all of its descendants (that is the set containing row with id @x and recursively any rows that have a parent_id in this set) sorted in pre-order:

select * from foo where parent_id=DescendantOf(@x) sort by Preorder

What SQL statement can I use? (modifications to table structure allowed if needed)

Also I would like to find the root id of a given element:

select RootOf(@x) from foo

How can I do that?

Can MySQL handle this efficiently or do I need to maintain my own index or auxillary table?

AFAIK there is no such functonality in MySQL built-in... Oracle has a feature called "hierarchical query" which does what you want...

In MySQL You can implement/simulate it although the "how" is rather complex - for a very good walkthrough see this article .

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