将加入的 table 限制为一个结果 Mssql

Limiting joined table to one result Mssql

我有两张表,一张存储一般信息,一张存储评论。

结构是表一中的一条记录在表二中可以有多个对应的结果。 但是我正在尝试编写一个查询,从 table one 中提取所有内容,并且仅从 table 2.

中提取最后一条评论

例如,假设 表一 中有一个用户,他们在 表二 中有 5 条评论,我想要的查询是从 表一 中拉人,只从 表二 .

中拉出最后一条评论

我在下面有这个查询,但是这将从 表 one 中提取所有内容,这是我想要的,但是如果 表中的记录有多个记录一个它会把他们全部带进来。

快速示例

Query results
ID  Field two  Field three  Field four     field out of table 2
1      Data       Data          Data           Comment 1
2      Data       Data          Data           Comment 1
2      Data       Data          Data           Comment 2
3      Data       Data          Data           Comment 1
4      Data       Data          Data           Comment 1
5      Data       Data          Data           Comment 1

如您所见,ID 为 2 的记录有两条评论,它被拉入两次,我想要的只是要显示的最后一条评论:

SELECT Qualitycontrol.ID, Qualitycontrol.MachineNo, Qualitycontrol.Description,    
    Qualitycontrol.CreatedTime, Qualitycontrol.ProductCode, Qualitycontrol.WorkOrder, 
    Qualitycontrol.Quantity, QualityControl_Comments.Comment
FROM Qualitycontrol 
LEFT OUTER JOIN QualityControl_Comments
           ON Qualitycontrol.ID = QualityControl_Comments.QCUID
WHERE (Qualitycontrol.CreatedTime 
        BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
ORDER BY Qualitycontrol.MachineNo

执行 OUTER APPLY 而不是 LEFT JOIN:

SELECT Qualitycontrol.ID, Qualitycontrol.MachineNo, Qualitycontrol.Description,  
       Qualitycontrol.CreatedTime, Qualitycontrol.ProductCode, Qualitycontrol.WorkOrder, 
       Qualitycontrol.Quantity, Qc.Comment
FROM Qualitycontrol 
OUTER APPLY (
   SELECT TOP 5 Comment
   FROM QualityControl_Comments
   WHERE Qualitycontrol.ID = QCUID
   ORDER BY ... DESC -- whatever defines order in QualityControl_Comments
) AS Qc(Comment)                  
WHERE (Qualitycontrol.CreatedTime BETWEEN CAST(GETDATE() AS DATE) AND DATEADD(DAY, 1, CAST(GETDATE() AS DATE)))
ORDER BY Qualitycontrol.MachineNo

您可以执行 JOIN 并根据 MAX(CommentId) 获取每条记录的最后一条评论。添加到您的 WHERE 子句中的类似内容应该有效:

AND qcc.ID = (SELECT MAX(ID) FROM QualityControl_Comments WHERE QCID = qc.ID)

完整查询(带别名):

SELECT  qc.ID ,
        qc.MachineNo ,
        qc.Description ,
        qc.CreatedTime ,
        qc.ProductCode ,
        qc.WorkOrder ,
        qc.Quantity ,
        qcc.Comment
FROM    Qualitycontrol qc
LEFT JOIN QualityControl_Comments qcc ON qc.ID = qcc.QCUID
WHERE   ( qc.CreatedTime BETWEEN CAST(GETDATE() AS DATE)
                                     AND     DATEADD(DAY, 1,
                                                     CAST(GETDATE() AS DATE)) )
        AND qcc.ID = (SELECT MAX(ID) FROM QualityControl_Comments WHERE QCID = qc.ID)
ORDER BY qc.MachineNo