使用嵌套查询创建视图

时间:2017-09-25 19:02:12

标签: sql

 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 ) 

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

1 个答案:

答案 0 :(得分: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

您只需要知道如何加入这些子查询。在你的情况下,我相信这是表格代码,如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
  )