简体   繁体   中英

MySQL query: select the pages of the first generation only?

I want to select the children pages ( first generation ) that derived from parent pages but not the children pages ( second generation , 3rd, etc) derived from the first generation , for instance,

pg_id     pg_title      parent_id
1         A             1            
2         B             2
3         C             1
4         d             1
5         e             1
6         f             4
7         g             4
8         k             5
9         l             3
10        j             3

So I want to get a result like this,

pg_id     pg_title      parent_id
3         C             1
4         d             1
5         e             1

The query below will select the generations branched from the first generation ,

$sql = "
    SELECT *
    FROM root_pages
    WHERE root_pages.parent_id != root_pages.pg_id
    ORDER BY pg_created DESC
    ";

How can I get the first generation only?

This should do it, if I'm understanding your question right.

 SELECT * 
 FROM root_pages 
 WHERE parent_id IN (
     SELECT pg_id 
     FROM root_pages 
     WHERE parent_id = pg_id
 ) AND
 parent_id != pg_id

For first generation only :

 SELECT * 
 FROM root_pages 
 WHERE parent_id = (
     SELECT pg_id 
     FROM root_pages 
     WHERE parent_id = pg_id order by pg_id asc limit 0, 1
 )

and ofcourse to remove self your logic can be added... ie. parent_id <> pg_id

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