通过连接三个表来创建视图

时间:2015-08-17 19:09:23

标签: sql join inner-join outer-join jointable

我正在尝试加入三张桌子。一个表具有简档信息,第二个表具有许可信息,第三个表具有排放信息。

表1:会员信息

No, 
Name, 
Sex, 
DBO, 
CaseNo, 
SeqNum,
StartDate,
......

表2:身份验证信息

No,
Name,    
DBO,
CaseNo,
SeqNum,
StartDate,
Admin_1,
Admin_2,
Admin_3,
...

表3:出院信息

CaseNo,
SeqNum,
DisDate,
DisRea,
...

这是我的疑问:

Select    a.no, 
          a.Name, 
          a.Sex, 
          a.DBO, 
          a.CaseNo, 
          a.SeqNum,
          a.StartDate,
          b.Admin_1,
          b.Admin_2,
          b.Admin_3,
          c.DisDate,
          c.DisRea
 from     dbo.mem_information as a inner join dbo.auth_information as b on b.caseno = a.caseno AND 
          b.seqnum = a.seqnum AND        
          b.StartDate = a.StartDate 
          inner join dbo.discharge_information as c ON c.caseno = b.caseno AND
          c.seqnum = b.seqnum 

我的结果示例:

 Name   Sex     DBO     CaseNo  SeqNum  Admin_1  Admin_2 Admin_3 DisDate DisRea
  Jones   M    19980615    23      1       SING
  Jones   M    19980615    23      1               LAUGH
  Smith   F    19960212    24      1       SING

期望的结果:

 Name  Sex     DBO     CaseNo  SeqNum  Admin_1  Admin_2 Admin_3 DisDate DisRea
 Jones   M    19980615    23      1     SING     LAUGH            
 Smith   F    19960212    24      1     SING

可能还没有任何放电数据,但我希望这些字段显示为NULL。

2 个答案:

答案 0 :(得分:1)

如果没有放电数据,那么在Null字段旁边有解决方案,那么可能没有条目。你应该使用左连接来组合表& discharge_information'。 sql查询如:

Select    a.no, 
          a.Name, 
          a.Sex, 
          a.DBO, 
          a.CaseNo, 
          a.SeqNum,
          a.StartDate,
          b.Admin_1,
          b.Admin_2,
          b.Admin_3,
          c.DisDate,
          c.DisRea
 from     dbo.mem_information as a inner join dbo.auth_information as b on b.caseno = a.caseno AND 
          b.seqnum = a.seqnum AND        
          b.StartDate = a.StartDate 
          left join dbo.discharge_information as c ON c.caseno = b.caseno AND
          c.seqnum = b.seqnum;

请参阅联接LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

的用法

答案 1 :(得分:1)

由于您没有提供任何样本数据,因此不确定如何测试,但我假设您正在寻找类似的内容:

$query = $this->Users->find('all', [
    'conditions' => [
        'token' => $token,
        'modified >' =>  new \DateTime('-2 hours'),
    ],
    'limit' => 1,
]);