2014-11-05 91 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