选择联接表使用的最大行数最大其他行差

时间:2019-01-03 21:21:36

标签: sql oracle

我有一个树表table_1,table_2和table_3,其结构为

表_1

enter image description here

table_2

enter image description here

table_3

enter image description here

在table_1中,我有一个unit_id,这很普遍,我想在所有表中选择数据,例如table_2和table_3中使用的unit_id = 5,建筑物行是6,地块行是2,我想选择6行building_id,building_area以及两行parcel_id和parcel_area旁边,对于unit_id = 6,则相反为4行宗地和两行建筑物,当unit_id = 7时为一排建筑物,在unit_id = 8时为一排地块。

select result example 


unit_id      building_id    building_area    parcel_id     parcel_area
   5            2                20             15             20
   5            3                10            null           null
   5            4                30            null           null
   5            5                15             16             10
   5            7                25            null           null
   5            8                15            null           null
   6           null             null            21             30 
   6           null             null            22             50
   6            9                18             23             80
   6            10               20             24             70
   7            30               10            null           null  
   8           null             null            27             52   

2 个答案:

答案 0 :(得分:0)

似乎您想离开table_2table_3table_1

SELECT t1.unit_id,
       t2.building_id,
       t2.area building_area,
       t3.parcel_id,
       t3.area parcel_area
       FROM table_1 t1
            LEFT JOIN table_2 t2
                      ON t2.unit_id = t1.unit_id
            LEFT JOIN table_3 t3
                      ON t3.unit_id = t1.unit_id;

答案 1 :(得分:0)

您确实希望所有三个表之间都保持左连接,但是通过查看示例数据,您似乎需要表2和3之间的关系才能包括该区域。

那将是:

SELECT 
    t1.unit_id,
    t2.building_id,
    t2.area AS building_area,
    t3.parcel_id,
    t3.area AS parcel_area
FROM 
    table_1 AS t1
    LEFT JOIN table_2 AS t2
        ON  t2.unit_id = t1.unit_id
    LEFT JOIN table_3 AS t3
        ON  t3.unit_id = t1.unit_id
        AND t3.area = t2.area