如何跨四个表加入SQL查询?

时间:2012-02-23 16:21:35

标签: sql tsql

我对SQL不是很好,所以我会发布我正在使用的表和我尝试过的表。

表1

Installation
   id

表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

5 个答案:

答案 0 :(得分:2)

这个怎么样:

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 :(得分: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 :(得分: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编辑了Assignment和AssignmentException,并添加了WHERE ae.type > 0
  • 您说您需要安装ID 12345,所以我加入了该表并更改了WHERE

希望这有帮助。

答案 3 :(得分: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

您不需要安装表,因为其中没有额外数据 - Project中的InstallationID足以识别安装。这假设在安装和项目之间存在PK / FK引用约束,并且它由DBMS强制执行

答案 4 :(得分: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
    )