从父母表中选择孙子,取决于孩子的类型

时间:2015-02-03 06:39:44

标签: mysql database-design

我有以下五个表:

       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 |
+--+------+-------+                      +--+------+-------+

我正在尝试从以上五个表中进行选择,以便得到与此类似的结果:

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

请注意,我认为只有女儿可以拥有GrandDaughters,只有Sons才能拥有GrandSons。根据父母的孩子是儿子还是女儿,我需要让第三栏分别是GrandSon或GrandDaughter。如果不进行多个查询,这是否可行?

1 个答案:

答案 0 :(得分:1)

尝试tis:

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