RequestIDでグループ化された最大DateStampを取得するActionテーブルから派生テーブルを作成できます(これにより、各RequestIDの最新のDateStampが得られます)。派生テーブルを取得したら、特定のRequestIDに一致する最新のDateStampを持つアクションテーブルの行のアクションテーブルに結合し直すことができます。
SELECT
P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
INNER JOIN
(SELECT RequestID, MAX(DateStamp) AS MostRecentDateStamp
FROM Action GROUP BY RequestID) AS MostRecentAction
ON R.ID = MostRecentAction.RequestID
INNER JOIN Action AS A
ON
MostRecentAction.RequestID = A.RequestID
AND
MostRecentAction.MostRecentDateStamp = A.DateStamp
INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN Line AS L ON R.LineID = L.ID
INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN Status AS S ON A.StatusID = S.ID
または、別のオプションは、ここでKarwin氏が示したアプローチを取ることです
。MySQLのテーブルから単一の行を結合します。
SELECT
P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
INNER JOIN Action AS A
ON
R.ID = A.RequestID
LEFT JOIN Action AS A2
ON
A.RequestID = A2.RequestID
AND
A.DateStamp < A2.DateStamp
INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN Line AS L ON R.LineID = L.ID
INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN Status AS S ON A.StatusID = S.ID
WHERE A2.RequestID IS NULL
私はカーウィン氏が使用するアプローチが好きです。特に、あなたが持っているような構造との関係を扱うときはそうです。
SELECT
P.ID AS PacketID, R.ID AS RequestID, A.ID AS ActionID, A.EmpID, P.DateStamp,
RQ.Description AS RequestType, L.Description AS Line, R.PartNo, R.Workorder,
R.Qty, RZ.Description AS ReasonType, R.MTF, S.Description AS Status
FROM Packet AS P
LEFT OUTER JOIN Request AS R ON R.PacketID = P.ID
INNER JOIN Action AS A
ON
R.ID = A.RequestID
LEFT JOIN Action AS A2
ON
A.RequestID = A2.RequestID
AND
(A.DateStamp < A2.DateStamp OR (A.DateStamp = A2.DateStamp AND A1.RequestID < A2.RequestID))
INNER JOIN RequestType AS RQ ON R.RequestTypeID = RQ.ID
INNER JOIN Line AS L ON R.LineID = L.ID
INNER JOIN ReasonType AS RZ ON R.ReasonTypeID = RZ.ID
INNER JOIN Status AS S ON A.StatusID = S.ID
WHERE A2.RequestID IS NULL