首页 > 技术文章 > left join 取一条数据

zhongxinWang 2015-08-31 17:42 原文

产品生产过程中要记录产品在制作过程中的不良历史,即使在一个工序,也可以产生多条不良历史记录,所有的不良信息保存在B表中。假设产品在打包工序,存放打包工序成品参数记录的表A,数据是唯一的。但在打包过程中,产生的不良信息,可以有多条。然而,产品在当天的工序报表中,产品的最终不良信息,只是取最终的一次记录为结果。使用关联查询A表,带出的B表信息,只需要最后一条。

1.先从B表中只获取最新的结果集

select * from AkBadInput a where Id=(select MAX(Id) from AkBadInput b where b.RepairKey=a.RepairKey and b.Barcode=a.Barcode and b.Process=a.Process)

2.通过关联上面的结果集,获取最新唯一的关联结果

select AkFqc.*,c.JudgeResult
from AkFqc left join 
(select * from AkBadInput a where Id=(select MAX(Id) from AkBadInput b where b.RepairKey=a.RepairKey and b.Barcode=a.Barcode and b.Process=a.Process)) c
on AkFqc.Id=c.RepairKey and AkFqc.BarCode=c.Barcode and c.Process='FQC'

 

推荐阅读