2012-02-23 51 views
1

我對SQL不太好,所以我會發布我正在使用的表格以及我嘗試過的表格。如何在四個表中加入SQL查詢?

表1

表2聯結到1和

Project 
    id 
    installationid 
    name 

表3聯結到2

Assignment 
    id 
    projectid 

表4鏈接到3

AssignmentException 
    id 
    assignmentid 
    type 

我想找到Project.name其中AssignmentException.type> 0爲Installation.id = 12345.我有最多的經驗是簡單的內部連接。以下是我沒有考慮到Installationid的非工作嘗試。關於你的代碼如何工作的簡短解釋也將不勝感激。

select * from ( 
    Assignment INNER JOIN AssignmentException ON Assignment.id = AssignmentException.assignmentID) 
    INNER JOIN Project ON Assignment.projectid = Project.id 
    WHERE AssignmentException.type > 0 
+0

似乎沒有一種AssignmentException與任何其他方法相關的方法表。我猜你剛剛在那裏錯過了'assignmentid'? – 2012-02-23 16:25:32

+0

@MattGrande - 感謝您指出了這一點,我更新了我的答案,以包括遺忘的作業 – mrtsherman 2012-02-23 16:28:28

回答

2

如何: - 在InstallationID在項目足以識別安裝

SELECT p.name 
FROM AssignmentException ex 
    JOIN Assignment a ON ex.id = a.AssignmentId 
    JOIN Project p ON a.ProjectId = p.Id 
WHERE ex.type > 0 
    AND p.InstallationId = 12345 
1
select p.Name 
from Project P 
join Assignment A on A.projectid = P.id 
join AssignmentException AE on AE.id=A.id 
where AE.AssignmentException>0 and P.installationid = 12345 
+2

假設安裝和項目之間的PK/FK參考約束由DBMS強制執行,則沒有安裝有用的數據。 – 2012-02-23 16:27:58

1

我認爲你在尋找這樣的事情:

SELECT p.Name 
FROM Project p 
INNER JOIN Assignment a ON a.projectid = p.id 
INNER JOIN AssignmentException ae ON ae.assignmentid = a.id 
INNER JOIN Installation i ON i.id = p.installationid 
WHERE ae.type > 0 AND i.id = 12345 

說明:

  • 您所需要的項目名稱,因此,這就是我開始(前兩個線)。
  • 你說你需要異常類型,所以我JOIN ED分配和AssignmentException,並添加WHERE ae.type > 0
  • 你說你需要安裝ID 12345,所以我加入了該表,並改變了WHERE

希望這幫助。

+1

假設安裝和項目之間的PK/FK參考約束由DBMS強制執行,則沒有安裝的有用數據。 – 2012-02-23 16:29:19

+0

是的,我想我不需要加入安裝。只需檢查Project.installationid。 – 2012-02-23 16:35:25

1
SELECT p.name 
    FROM AssignmentException AS e 
    JOIN Assignment   AS a ON a.id = e.assignmentID 
    JOIN Project    AS p ON p.id = a.projectid 
WHERE e.type > 0 
    AND p.installationID = 12345 

,因爲沒有多餘的數據,它不需要安裝表。這假定在安裝和項目之間有一個PK/FK參考約束,並且它由DBMS強制執行

0
SELECT P.Name 
FROM Project AS P 
--Using EXISTS as you do not need to join unless it is in your output 
--More often, this results in better performance 
WHERE 
    --This pulls in only those projects with Installation ID = 12345 
    P.InstallationId = 12345 
    --This pulls in only projects with Assignments 
    --that have Assignment Exceptions of Type > 0 
    AND EXISTS 
    (
     SELECT 1 
     FROM Assignment AS A 
      JOIN AssignmentException AS AE ON A.ID = AE.ID 
     WHERE A.ProjectId = P.Id AND AE.Type > 0 
    )