2

我需要使用联合将两个具有一对多关系的表结合起来,但没有成功。

在此处输入图像描述 我一直在尝试使用此代码

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 中找到对应的。

4

2 回答 2

4

秘诀是加入 tbl_equipwarranty 两次 - 使用 2 个不同的别名。一份服务保修,一份产品保修。您可以通过将服务类型指定为连接的一部分来执行此操作。以下使用 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'
于 2014-11-05T04:23:54.280 回答
3

只有当您在表中为设备 ID 提供唯一的保修 ID 时,这才会为您提供所需的结果。

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'
于 2014-11-05T04:37:32.980 回答