SQL query to select only grandchildren

后端 未结 5 1433
无人及你
无人及你 2021-01-12 16:04

I\'m pretty new to SQL, trying to wrap my head around it, but it\'s getting a little confusing. Here\'s a simplified version of what I\'m working with.

I have this

5条回答
  •  无人及你
    2021-01-12 16:18

    This is without JOIN statement, but as a SQL learner, I find it as easier:

    1. For grandchildren:

      SELECT grandparent.name AS Grandparents, grandchild.name AS Grandchildren 
      FROM people AS grandparent, people AS parent, people
      AS grandchild WHERE grandchild.parent_id = parent.id 
      AND parent.parent_id = grandparent.id;
      
    2. For children:

      SELECT parent.name as Parent, child.name AS Child 
      FROM people AS parent, people AS child 
      WHERE child.parent_id = parent.id AND parent.parent_id = 0;
      
    3. And for all children-parent pairs:

      SELECT parent.name as Parent, child.name AS Child 
      FROM people AS parent, people AS child 
      WHERE child.parent_id = parent.id;
      

    It took me a while, but it was fun :D

提交回复
热议问题