2014-11-05 93 views
2

我需要将两个表结合成一对多关系,但使用union而不成功。如何将表与1对多关系合并为1行记录

enter image description here 我一直在尝试使用此代码

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

除了你的第二和第三个查询的别名看起来完全相同吗? – FuzzyTree 2014-11-05 04:09:39

+0

抱歉关于相同。我在我的代码中纠正了它,但它仍然显示错误。 – Mandz 2014-11-05 04:58:03

回答

4

秘诀是加入tbl_equipwarranty两次 - 使用2个不同的别名。一个用于服务保修,另一个用于产品保修。您可以通过将servicetype指定为连接的一部分来完成此操作。下面使用ANSI连接,因此可能会在火鸟和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

你是一个拯救生命的人。有了这些知识,我现在可以轻松地使用1选择语句显示报告。我打算使用3个选择并将它与1个记录集合并在同一时间显示它作为我的最后手段。感谢您的新知识^ _^ – Mandz 2014-11-05 04:39:08

+0

@Mandz很高兴能有所帮助:-) – Donal 2014-11-05 04:40:40

+0

我还有一个问题。现在我需要将表与1到N的关系组合起来,但现在我只需要N的最后一个值。你能帮助我吗? http://stackoverflow.com/questions/26882396/combine-tables-with-1-to-n-relationship-into-1-line-of-record-with-the-last-valu – Mandz 2014-11-12 08:35:23

3

这会给你所需的结果,只有当你有礼物表的equipmentid独特warrantyid。

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' 
+0

我试过你的代码先生,它也在工作。对不起,如果不能选择你发布的答案,因为我刚才已经选择了我的答案。不管怎么说,多谢拉。^_^ – Mandz 2014-11-05 04:46:38

+0

@Mandz没有问题的人.. :) – 2014-11-05 06:19:47