views:

14

answers:

2

Let's say I have 2 tables. I want join them so that for every account I get 1 row where the account's information is there PLUS the primaryContact's information appended to the table. Is this possible? ID's are unique keys.

ACCOUNT TABLE

 accountid    |    name    |    income    |    primaryContact  

 123456789     Jack Johnson    120,000      Jill Johnson

CONTACT TABLE

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

 123456789           13459284      Jill Johnson    1355 Fir street  Yorba         Washington      USA 

RESULT TABLE

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

 123456789     Jack Johnson    120,000      Jill Johnson           1355 Fir street   Yorba           Washington      USA
+2  A: 
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
Martin Smith
There's no `CONTACT.primarycontact` column ;)
OMG Ponies
So if wanted to include those accounts without a primaryContact (null) then I do a left outer join? Thanks.
Ehsan
@Ehsan - Yes. By the way have you considered adding a `contactid` column to account rather than name. Being numeric it might be a bit quicker for joins also if people change their name (e.g. get married) there is less to update.
Martin Smith
+2  A: 

Use:

   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

This will show you all the accounts. If there's a primary contact, the values will be populated--otherwise the references to the CONTACT table will be NULL. If you don't want this behavior, omit the "LEFT" from the query:

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

OMG Ponies
+1 Thanks for correcting my error!
Martin Smith
Thanks! You're correct, I should've been more specific. forgot about those nulls.
Ehsan