Hi all!
I have 3 tables
RECORDS
Id, Record_Id
ITEMS
Id, Record_Id
ARTICLES
Id, Record_Id
I need to join RECORDS table 3 times R1,R2,R3 and get count of items R2 and R3 have and count articles that R3 has.
R2 must have ITEMS and R3 must have items, R3 may have articles. R1 may have multiple children and R2 may have multiple children.
Solution I'm using is following, but distinct makes it slow...
select r1 as ParentRecordId,count(distinct i1) as Volumes,count(distinct i2) as Numbers, count(distinct a1) as Articles
from
(
select r1.id as r1,i1.id as i1,i2.id as i2,a.id as a1
from records r1 inner join records r2 on r1.id=r2.record_id
inner join records r3 on r2.id=r3.record_id
inner join items i1 on r2.id=i1.record_id
inner join items i2 on r3.id=i2.record_id
left join articles a on a.record_id=r3.id
) as sel
group by r1
order by 1
Regards
Meelis