从多个表创建父子视图

knpiaxh1  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(456)

我有以下表格:

CREATE TABLE Equipment (Id int,Name varchar(20),SubAreaId int);

INSERT INTO Equipment (Id, Name ,SubAreaId)
VALUES  (1, 'EquipmentA',1),
        (2, 'EquipmentB',1),
        (3, 'EquipmentC',2),
        (4, 'EquipmentD',2);

CREATE TABLE SubArea (Id int,Name varchar(20),AreaId int);

INSERT INTO SubArea (Id,Name,AreaId)
VALUES  (1, 'SubAreaA',1),
        (2, 'SubAreaB',2),
        (3, 'SubAreaC',2);

CREATE TABLE Area (Id int,Name varchar(20),SiteId int);

INSERT INTO Area (Id,Name,SiteId)
VALUES  (1, 'AreaA',1),
        (2, 'AreaB',1),     
        (3, 'AreaC',1);        

CREATE TABLE Site (Id int,Name varchar(20));
INSERT INTO Site (Id,Name)
VALUES  (1, 'Site');

希望获得显示以下内容的视图:

链接到我创建架构的sql fiddle:http://www.sqlfiddle.com/#!18/53d1ce/2号
编辑:添加了areac和subreac,它们不应该显示在视图中,因为它们没有连接到任何设备

vs3odd8k

vs3odd8k1#

这是一个 union all :

select s.name, a.name
from area a join
     site s
     on a.siteid = s.id
union all
select a.name, sa.name
from subarea sa join
     area s
     on sa.areaid = a.id
union all
select sa.name, e.name
from equipment e join
     subarea sa
     on sa.subareaid = sa.id;

相关问题