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

时间:2010-09-02 22:56:10

标签: sql sql-server sql-server-2005 tsql

假设我有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

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:2)

使用:

   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

See this link for a visual representation of the different JOINs ...