将具有1到N关系的表组合成1行记录和N记录的最后一个值

时间:2014-11-12 08:30:14

标签: mysql sql firebird firebird2.5

我需要修改我之前的帖子 如何将具有1对多关系的表组合成1行记录

how to combine tables with 1 to many relationship into 1 line of record

现在我的问题是我的记录现在有1对多的关系。我需要展示的只是最后一条记录,并将其合并为一行 表tbl_equipment和tbl_warranty

enter image description here

这是所需的输出 enter image description here

这是我正在尝试实施的代码

 SELECT
 a.equipmentid,
 a.codename,
 a.name,
 a.labelid,
 a.ACQUISITIONDATE,
 a.description,
 a.partofid,
 w1.warrantyid as serviceidwarranty,
 w1.startdate,
 w1.enddate,
 w2.warrantyid as productidwarranty,
 w2.startdate,
 w2.enddate,
 s.equipstatusid,
 l.equiplocationid FROM TBL_EQUIPMENTMST a
 left JOIN tbl_equipwarranty w1
 ON w1.equipmentid=a.equipmentid and w1.serviceproduct = 'service'
 left JOIN tbl_equipwarranty w2
 ON w2.equipmentid=a.equipmentid and w2.serviceproduct = 'product'
 left join tbl_equipstatus s
 on a.equipmentid = s.equipmentid
 left join tbl_equiplocation l
 on a.equipmentid = l.equipmentid  WHERE a.equipmentid = '112'

我只想在输出中显示保修产品和保修服务的最后一个值的1条记录。任何人都可以指导我如何修改我的代码,以便当我尝试加入上面列出的所有表时,只能将最后一个保修记录作为输出产生1条记录。 我使用firebird作为数据库。如果你在mysql中有一个解决方案,请告诉我,并试着找到firebird中的对应物。

2 个答案:

答案 0 :(得分:0)

with summary as(
select e.equipmentid ,e.Codename,e.Name,w.warrantyid ,w.Satartdate ,w.Enddate,w.warrantytype 
from Eqp e
join Warranty w
on(w.equipmentid =e.equipmentid )
where w.warrantyid =3)

select *,w.warrantyid,w.Satartdate ,w.Enddate,w.warrantytype
from summary s
join  Warranty w
on s.Satartdate =w.Satartdate and s.Enddate =w.Enddate 
where w.warrantyid =4

答案 1 :(得分:0)

在阅读了Barmar关于解决问题的评论之后。我想出子查询可以解决我的问题。子查询对我来说是个新词。我研究如何使用子查询,并在下面提出了一个解决方案。如果我的代码错误或如何提高查询性能,你可以纠正我

SELECT 
    a.equipmentid,a.codename,a.name,a.labelid,a.ACQUISITIONDATE,a.description,a.partofid,
    w1.warrantyid as serviceidwarranty,w1.startdate,w1.enddate,
    w2.warrantyid as productidwarranty,w2.startdate,w2.enddate,
    s.equipstatusid,
    l.equiplocationid 
FROM 
    TBL_EQUIPMENTMST a
left JOIN
    (select first 1 *
     from tbl_equipwarranty 
     where equipmentid='112' and serviceproduct = 'service'
     order by warrantyid desc) w1 ON w1.equipmentid = a.equipmentid 
                                     and w1.serviceproduct = 'service'
left JOIN
    (select first 1 *
     from tbl_equipwarranty 
     where equipmentid = '112' and serviceproduct = 'product'
     order by warrantyid desc) w2 ON w2.equipmentid = a.equipmentid 
                                     and w2.serviceproduct = 'product'
left join
    (select first 1 *
     from tbl_equipstatus 
     where equipmentid = '112'
     order by equipstatusid desc) s on a.equipmentid = s.equipmentid
left join
    (select first 1 *
     from tbl_equiplocation 
     where equipmentid = '112'
     order by equiplocationid desc) l on a.equipmentid = l.equipmentid  
WHERE 
     a.equipmentid = '112'