2016-04-23 8 views
0

Ich habe zwei Tabellen: tblOrganisations und tblContacts. Ich habe eine Abfrage, die Organisationen zurückbringt. Ich möchte auch zwei Kontakte unterschiedlicher Art (primär = 1, alternativ = 2) in Verbindung mit einer Organisation zurückbringen. Wie auch immer, ich stecke fest, wie man mehrere Felder für mehrere Kontakte von einem Tisch als verschiedene Dinge zurückbringt.Wählen Sie zwei Elemente aus einer Tabelle als zwei verschiedene Dinge

Bis jetzt kann ich ihre ReferenceIDs als PrimaryID und SecondaryID erhalten.

SELECT tblOrganisations.* 
     , (SELECT tblContacts.ReferenceID 
      FROM tblContacts 
      WHERE tblOrganisations.ReferenceID = tblContacts.tblOrganisations_ReferenceID 
      AND tblContacts.tblContactTypes_ReferenceID = 1 
     ) AS PrimaryID 
    , ( SELECT tblContacts.ReferenceID 
      FROM tblContacts 
      WHERE tblOrganisations.ReferenceID = tblContacts.tblOrganisations_ReferenceID 
      AND tblContacts.tblContactTypes_ReferenceID = 2 
     ) AS SecondaryID 
FROM tblOrganisations 

Die obige Abfrage wird mir die Organisation und die referenceId die ihre Kontakte aus tblContacts als PrimaryID und SecondaryID für die zwei verschiedenen Arten von Kontakt ich will. Aber ich möchte mehr Felder für jeden Kontakt - Vorname, Nachname, Emailadresse usw.

Ich versuchte Zeug wie;

SELECT tblOrganisations.* 
     , 
     (SELECT tblContacts.ReferenceID AS PrimaryID , 
        FirstName AS PrimaryFirstName 
      FROM  tblContacts 
      WHERE  tblOrganisations.ReferenceID = tblContacts.tblOrganisations_ReferenceID 
        AND tblContacts.tblContactTypes_ReferenceID = 1 
     ) 
     , 
     (SELECT tblContacts.ReferenceID AS SecondaryID , 
        FirstName AS SecondaryFirstName 
      FROM  tblContacts 
      WHERE  tblOrganisations.ReferenceID = tblContacts.tblOrganisations_ReferenceID 
        AND tblContacts.tblContactTypes_ReferenceID = 2 
     ) 
FROM tblOrganisations 

Aber das macht eigentlich nichts in PrimaryID bringen, SecondaryID, PrimaryFirstName etc

Vielen Dank für jede Hilfe oder Zeiger :)

Antwort

2

Die Tabelle mit den Soll-Werten werden muss zweimal verbunden In diesem Fall wären es tblcontacts.

SELECT 
o.*, 
c1.referenceid AS PrimaryID,c1.firstname as primaryfirstname, 
c2.referenceid AS SecondaryID,c2.firstname as secondaryfirstname 
FROM tblOrganisations o 
JOIN tblContacts c1 on o.ReferenceID = c1.tblOrganisations_ReferenceID 
JOIN tblContacts c2 on o.ReferenceID = c2.tblOrganisations_ReferenceID 
WHERE c1.tblContactTypes_ReferenceID = 1 and c2.tblContactTypes_ReferenceID = 2 
+0

Vielen Dank, das funktioniert ein Genuss! Ich habe stundenlang herumgesprochen und gegoogelt - und das war so einfach! Nochmals vielen Dank, nette Eins :) – luke

Verwandte Themen