2014-11-05 2 views
2

조합을 사용하여 1 대 다수 관계가있는 테이블을 두 개 결합해야하지만 성공하지 못합니다. 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 

이 사람이 내 이미지 내 예상 출력을 생성하는 방법 나를 도울 수이 코드를 사용하려고했습니다. 파이어 버드를 데이터베이스로 사용하고 있습니다. mysql에서 해결책을 찾았다면 친절하게도 파이어 버드에있는 답을 찾아보십시오.

+0

두 번째 및 세 번째 검색어가 동일한 것으로 보이는 별칭을 제외하고는? – FuzzyTree

+0

동일한 것에 대해 미안합니다. 코드에서 오류가 있지만 오류는 여전히 수정되었습니다. – Mandz

답변

4

비밀은 tbl_equipwarranty에 두 번 가입하는 것입니다. 두 가지 다른 별칭을 사용합니다. 하나는 서비스 보증을위한 것이며 다른 하나는 제품 보증을위한 것입니다. 조인의 일부로 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 select 문을 사용하여 보고서를 쉽게 표시 할 수 있습니다. 저는 3을 선택하여 하나의 레코드 세트와 결합하여 그것을 최후의 수단과 동시에 표시 할 계획이었습니다. 새로운 지식을 가져 주셔서 감사합니다.^_^ – Mandz

+0

@Mandz Glad가 도와 드리겠습니다 :-) – Donal

+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

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

+0

@Mandz 아니 문제 남자 .. :) –

관련 문제