2010-09-02 6 views
1

Disons que j'ai 2 tables. Je veux les joindre de sorte que pour chaque compte je reçois 1 ligne où l'information du compte est là PLUS les informations du contact principal ajouté à la table. Est-ce possible? Les ID sont des clés uniques.SQL 2005 - deux tables Rejoindre un ID,

COMPTE TABLEAU

accountid | name | income | primaryContact 

123456789  Jack Johnson 120,000  Jill Johnson 

CONTACT TABLEAU

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

123456789   13459284  Jill Johnson 1355 Fir street Yorba   Washington  USA 

RESULT TABLEAU

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

123456789  Jack Johnson 120,000  Jill Johnson   1355 Fir street Yorba   Washington  USA 

Répondre

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

Il n'y a pas 'colonne CONTACT.primarycontact';) –

+0

Donc, si voulu inclure ces comptes sans un primaryContact (null) alors je fais une jointure externe gauche? Merci. – EKet

+0

@Ehsan - Oui. D'ailleurs, avez-vous envisagé d'ajouter une colonne 'contactid' à un compte plutôt qu'à un nom. Étant numérique, il peut être un peu plus rapide pour les jointures si les gens changent de nom (par exemple, se marier) il y a moins à mettre à jour. –

2

Utilisation:

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 

Cela vous montrera tous les comptes. S'il y a un contact principal, les valeurs seront remplies - sinon les références à la table CONTACT seront NULL. Si vous ne voulez pas ce comportement, omettre la « gauche » de la requête:

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 Merci d'avoir corrigé mon erreur! –

+0

Merci! Vous avez raison, j'aurais dû être plus précis. oublié à propos de ces nulls. – EKet