代码之家  ›  专栏  ›  技术社区  ›  Koosh

用两组条件连接两个数据库

  •  1
  • Koosh  · 技术社区  · 6 年前

    我有两个数据库,我想拉到一个查询。 结构如下

    dB1

    tblA
    patientID     UniqueID    
    23            1787S
    25            0989S
    
    tblB
    patientID     ApptType       ApptDate
    23            1              1/1/2018
    25            2              1/1/2017
    

    DB2

    tblC
    patientID     UniqueID
    3             1787S
    
    
    tblD
    patientID    ApptType       AppDate
    3            1              2/2/2016
    

    这是非常简单的数据结构,但应该足以得到我需要的查询: 基本上,两个数据库中的许多患者都是相同的,但这就是为什么他们有不同的患者,这使得这变得困难。他们有同样的唯一身份证。

    我想找客户 DB1 那有 AppType = 1 . 然后希望加入 DB2 只选择那些 AppType=1 但是,仅显示具有匹配项的客户端 UniqueID

    结果如下:

    DB1_patientID         DB2_patientID         AppType        UniqueID
    23                    3                     1              1787S 
    

    所以我只看到这个客户机,因为在两个数据库中它都符合第一个条件- AppType=1 ,并且在两个数据库中,客户端具有相同的 UniqueID - 1787S

    这是我试过的,但我不确定这是否正确:

    Select a.patientID, c.patientID
    From ((tblA a inner join DB2.tblC c on (a.UniqueID = c.UniqueID)) inner join tblB b
    a.patientID = b.patientID) inner join DB2.tblD d on c.patientID = d.patientId
    group by a.patientId, c.patientID
    Having (b.appType = 1 and d.appType=1)
    

    这个查询给了我结果,但是由于我有成千上万条记录,很难验证是否一切都是正确的。

    1 回复  |  直到 6 年前
        1
  •  1
  •   DhruvJoshi    6 年前

    你的问题应该是

    select 
        DB1_patientID =   A.patientID,
        DB2_patientID =   C.patientID,
        AppType       =   D.ApptType
        UniqueID      =   C.uniqueid
    from
    tblA A
    join tblB B
        on B.patientID=A.patientID
        and B.ApptType=1
    join db2..tblC C
        on A.uniqueid=C.uniqueid
    join db2..tblD D
        on C.patientID=D.patientID
        and D.ApptType=1