I need to combine two tables with 1 to many relationship using union but to no success.
I've been trying to use this codeselect a.equipmentid,
a.codename,
a.name,
a.labelid,
a.ACQUISITIONDATE,
a.description
from TBL_EQUIPMENTMST a where
a.partofid = '57'
union all
select first 1 b.warrantyid, b.startdate, b.enddate from tbl_equipwarranty b
inner join TBL_EQUIPMENTMST c
on b.equipmentid=c.equipmentid
where c.partofid = '57' and b.servicetype='service' order by b.warrantyid desc
union all
select first 1 d.warrantyid, d.startdate, d.enddate from tbl_equipwarranty d
inner join TBL_EQUIPMENTMST e
on d.equipmentid=e.equipmentid
where e.partofid = '57' and d.servicetype='product' order by d.warrantyid desc
can anyone help me how to produce my expected output in my image. I am using firebird as a database. If you have a solution in mysql kindly tell me and ill try to find the counterpart in firebird.
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'
来源:https://stackoverflow.com/questions/26749492/how-to-combine-tables-with-1-to-many-relationship-into-1-line-of-record