2010-09-02 45 views
1

假設我有2個表。我想加入他們,這樣每個帳戶我都會得到1行帳戶的信息,並在主表中添加primaryContact的信息。 這可能嗎? ID是唯一的密鑰。SQL 2005 - 兩個表加入一些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
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 
+0

有沒有'CONTACT.primarycontact'列;) – 2010-09-02 23:09:46

+0

因此,如果希望包括那些帳戶沒有primaryContact(null),那麼我做一個左外連接?謝謝。 – EKet 2010-09-02 23:19:58

+0

@Ehsan - 是的。順便說一下,你有沒有考慮添加一個'contactid'列來說明問題而不是名稱。作爲數字,如果人們改變他們的名字(例如結婚),那麼加入可能會更快一些,但更新更少。 – 2010-09-02 23:25:46

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。如果你不希望這種行爲,忽略了「左」從查詢:

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 ...

+0

+1感謝您糾正我的錯誤! – 2010-09-02 23:23:28

+0

謝謝!你是對的,我應該更具體。忘了那些空位。 – EKet 2010-09-02 23:25:01