2017-09-25 194 views
0
Use Surveydb; 
create view VW_Service 
    As 
    (select A.id as 'Encounter ID' 
      ,A.startDateTime as 'Enconter StartDateTime' 
      ,A.endDateTime as 'Encounter EndDateTime' 
      ,B.id as 'Service ID' 
      ,B.startDateTime as 'Service StartDateTime' 
      ,B.endDateTime as 'Service EndDateTime' 
      ,C.label as 'Services Name Code Label' 
      ,C.symbol as 'Service Name Code Symbol' 
      ,C.system as 'Service Name Code System' 
    from Code C, 
      Encounter A, 
      Service B 
    where 
    a.id = b.encounterId 
    and c.id = b.nameCodeId) 
    JOIN 
    (select a.label as 'Service Status Code Label' 
      ,a.symbol as 'Service Status Code Symbol' 
      ,b.system as 'Services Status Code System' 
     from 
     Code a, Code b 
     Where 
     a.id = b.id) 

我试图创建一个包含三个表的视图,并且还需要自行连接其中一个表。上面的脚本是视图的单独查询。第一个查询由所有三个表组成,第二个子查询是来自代码表的自加入查询。我试图加入这两个查询。有什么想法吗?使用嵌套查询创建视图

+0

嗨,夫妇的问题开始。您使用的是哪种数据库引擎,其次是从上述SQL中获取的错误是什么?谢谢! –

+0

我想你是要求为上述查询optmizatrion。所以请张贴一些样本数据和您预期的O/P结果。 –

+0

这两个子查询有哪些常见字段?他们如何加入?一旦你指定我们可以写出其余的缺失部分。 – JNevill

回答

0

2个子查询的连接非常简单:您只需要2个子查询并按照常规表格进行连接。像这样:

select * 
from (select id from table a) as a 
join (select id from table b) as b 
    on a.id = b.id 

你只需要知道如何加入这些子查询。在你的情况下,我相信这是来自表Code,像id字段。

但是你的“自我加入”连线,你不需要它了,这将给你相同的结果:

join (select a.label as 'Service Status Code Label' 
     ,a.symbol as 'Service Status Code Symbol' 
     ,a.system as 'Services Status Code System' 
    from Code a 
)