从 parents table 中选择 grandchildren,取决于 child 的类型

Selecting grandchildren from parents table, dependant on child's type

我有以下五个表:

       Parents:          
    +--+---------+   
    |id|   name  |   
    +--+---------+   
    | 1|  lorem  |
    | 2|  ipsum  |   
    | 3|  lorem  |   
    +--+---------+

    Daughters:                                 Sons:
+--+------+-------+                      +--+------+-------+
|id|parent|  name |                      |id|parent|  name |
+--+------+-------+                      +--+------+-------+
| 1|   3  | lorem |                      | 1|   1  | lorem |
| 2|   1  | ipsum |                      | 2|   3  | ipsum |
| 3|   2  | lorem |                      | 3|   1  | lorem |
+--+------+-------+                      +--+------+-------+


    GrandDaughters:                          GrandSons:
+--+------+-------+                      +--+------+-------+
|id|parent|  name |                      |id|parent|  name |
+--+------+-------+                      +--+------+-------+
| 1|   3  | lorem |                      | 1|   1  | lorem |
| 2|   1  | ipsum |                      | 2|   3  | ipsum |
| 3|   1  | lorem |                      | 3|   2  | lorem |
+--+------+-------+                      +--+------+-------+

我正在尝试 select 从上面的五个表中得到类似于这样的结果:

Result
+------+-------------+-------------------------------+
| Name | Child's name| GrandSons/GrandDaughters name |
+------+-------------+-------------------------------+
| lorem|    ipsum    |                lorem          |
| lorem|    lorem    |                ipsum          |
| ipsum|    lorem    |                lorem          |
+------+-------------+-------------------------------+

请注意,我假设只有女儿可以有孙女,只有儿子可以有孙子。根据 Parent 的 child 是儿子还是女儿,我需要让第三列分别是孙子或孙女。不进行多个查询是否可行?

试试这个:

select p.name, d.name, g.name from parent p join daughters d on p.id = d.parent join granddaughters g on d.id=g.parent
union all
select p.name, s.name, g.name from parent p join sons s on p.id = s.parent join grandsuns g on s.id=g.parent