我需要使用union将两个表与1到多个关系组合在一起,但没有成功。
我一直在尝试使用此代码
select 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
任何人都可以帮助我如何在我的图像中产生我预期的输出。我使用firebird作为数据库。如果你在mysql中有一个解决方案,请告诉我,并试着找到firebird中的对应物。
答案 0 :(得分:4)
秘诀是加入tbl_equipwarranty两次 - 使用2个不同的别名。一个用于服务保修,一个用于产品保修。您可以通过将servicetype指定为连接的一部分来完成此操作。以下使用ANSI连接,因此可能适用于firebird和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'
答案 1 :(得分:3)
只有当您在表中列出了设备的唯一担保时,才能获得所需的结果。
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'