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

一个人想着一个人 提交于 2019-12-06 13:37:06

The secret is to join on tbl_equipwarranty twice - using 2 different aliases. One for the service warranty and one for the product warranty. You can do this by specifying the servicetype as part of the join. The following uses ANSI joins so will probably work in firebird and mysql:

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
FROM TBL_EQUIPMENTMST a 
INNER JOIN tbl_equipwarranty w1 
    ON w1.equipmentid = a.equipmentid AND w1.servicetype = 'service'
INNER JOIN tbl_equipwarranty w2 
    ON w2.equipmentid = a.equipmentid AND w2.servicetype = 'Product'
WHERE
a.partofid = '57'

This will give you required result only when you have unique warrantyid present for an equipmentid in table.

SELECT 
a.equipmentid,
a.codename,
a.name,
a.labelid,
a.ACQUISITIONDATE,
a.description,
a.partofid,
B.warrantyid AS serviceidwarranty,
B.Startdate,
B.Enddate,
C.warrantyid AS productidwarranty,
C.Startdate,
C.Enddate

FROM TBL_EQUIPMENTMST A
LEFT OUTER JOIN tbl_equipwarranty B ON A.equipmentid=B.equipmentid AND B.Servicetype='Service'
LEFT OUTER JOIN tbl_equipwarranty C ON A.equipmentid=C.equipmentid AND C.Servicetype='Product'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!