对于一个 sql 数据库管理员来说,这可能是一个简单的问题,但我是一个 C# 人,他只涉足数据库足够长的时间,以便在必要时让它们工作。
我有一个我设计的新数据库,里面只有很少的数据。
我需要一个用于生成视图的查询,但我似乎永远无法理解如何/何时使用 INNER 与 LEFT 连接。
APacket
可以有多个Request
条目(一个人请求 5 个不同的部分),每个Request
条目可以有不同的Action
条目(暂停、取消、特殊订单、完成等)。
我想创建一个生成以下数据表的查询:
SELECT
P.EmpID AS Requestor, P.DateStamp AS Submitted,
T.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder, R.Qty,
RT.Description AS ReasonType, S.Description AS Status, A.EmpID AS Stator, A.DateStamp AS Stated, R.MTF
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON (R.PacketID=P.ID)
LEFT OUTER JOIN Action AS A ON (A.RequestID=R.ID)
LEFT OUTER JOIN RequestType AS T ON (R.RequestTypeID=T.ID)
LEFT OUTER JOIN Line AS L ON (R.LineID=L.ID)
LEFT OUTER JOIN ReasonType AS RT ON (R.ReasonTypeID=RT.ID)
LEFT OUTER JOIN Status AS S ON (A.StatusID=S.ID)
Status
这将返回 5 行,但、Stator
和有一些 NULL 条目Stated
。
所以,我试着用 INNER JOIN 写这个:
SELECT
P.EmpID AS Requestor, P.DateStamp AS Submitted,
T.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder, R.Qty,
RT.Description AS ReasonType, S.Description AS Status, A.EmpID AS Stator, A.DateStamp AS Stated, R.MTF
FROM Packet AS P
INNER JOIN Request AS R ON (R.PacketID=P.ID)
INNER JOIN Action AS A ON (A.RequestID=R.ID)
INNER JOIN RequestType AS T ON (R.RequestTypeID=T.ID)
INNER JOIN Line AS L ON (R.LineID=L.ID)
INNER JOIN ReasonType AS RT ON (R.ReasonTypeID=RT.ID)
INNER JOIN Status AS S ON (A.StatusID=S.ID)
NULL 条目现在消失了,但现在我只返回了 3 行。
我怎么知道我应该使用哪个版本?...或者,我应该使用 LEFT 和 INNER 联接的组合吗?