SQL 2005 - 两个表加入一些ID,
问题描述:
假设我有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
答
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。如果你不希望这种行为,忽略了“左”从查询:
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
有没有'CONTACT.primarycontact'列;) – 2010-09-02 23:09:46
因此,如果希望包括那些帐户没有primaryContact(null),那么我做一个左外连接?谢谢。 – EKet 2010-09-02 23:19:58
@Ehsan - 是的。顺便说一下,你有没有考虑添加一个'contactid'列来说明问题而不是名称。作为数字,如果人们改变他们的名字(例如结婚),那么加入可能会更快一些,但更新更少。 – 2010-09-02 23:25:46