将连接表限制为一个结果Mssql

时间:2015-01-07 10:06:38

标签: php sql-server

我有两个表,一个存储一般信息,一个存放注释。

结构是表一中的记录可以在表二中有许多相应的结果。 但是,我正在尝试编写一个查询,从表一中提取所有内容,而只从表2 中提取最后一条评论。

例如,假设表格中有一个用户,并且他们在表格二中有5条评论,我想要的查询会从表中提取该人一个,只有表二中的最后一个评论。

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

快速示例

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

2 个答案:

答案 0 :(得分:1)

执行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

答案 1 :(得分:1)

您可以执行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