繁体   English   中英

SQL 2005 - 两个表加入一些id,

[英]SQL 2005 - two tables Join on some id,

假设我有2张桌子。 我想加入他们,以便每个帐户我得到1行帐户的信息在那里PLUS将primaryContact的信息附加到表格中。 这可能吗? ID是唯一键。

账户表

 accountid    |    name    |    income    |    primaryContact  

 123456789     Jack Johnson    120,000      Jill Johnson

联系表

parentAccountid    |contactid    |    name    |    street        |    city    |    state    |    Country

 123456789           13459284      Jill Johnson    1355 Fir street  Yorba         Washington      USA 

结果表

  accountid    |    name    |    income    |    primaryContact    |    street    |    city    |    state    |    country 

 123456789     Jack Johnson    120,000      Jill Johnson           1355 Fir street   Yorba           Washington      USA
SELECT a.accountid     ,
       a.name          ,
       a.income        ,
       a.primaryContact,
       c.street        ,
       c.city          ,
       c.state         ,
       c.country
FROM   account a
       JOIN contact c
       ON     a.accountid      = c.parentAccountid
       AND    a.primaryContact = c.name

采用:

   SELECT a.accountid,
          a.name,
          a.income,
          a.primaryContact,
          c.street,
          c.city,
          c.state,
          c.country
     FROM ACCOUNT a
LEFT JOIN CONTACT c ON c.parentaccountid = a.accountid
                   AND c.name = a.primarycontact

这将显示所有帐户。 如果存在主要联系人,则将填充值 - 否则对CONTACT表的引用将为NULL。 如果您不想要此行为,请忽略查询中的“LEFT”:

   SELECT a.accountid,
          a.name,
          a.income,
          a.primaryContact,
          c.street,
          c.city,
          c.state,
          c.country
     FROM ACCOUNT a
     JOIN CONTACT c ON c.parentaccountid = a.accountid
                   AND c.name = a.primarycontact

有关不同JOIN的直观表示,请参阅此链接 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM