sql - How do I combine two LEFT JOINS without getting crossover? -
i've got 2 queries i'd combine one, keep matrix effect when do.
select u.*, count(q.id) users u left join questions q on u.id = q.author_id group u.id
select u.*, count(a.id) users u left join answers on u.id = a.author_id group u.id
those queries give me count of 10 questions , 10 answers. when combine them below, question , answer count jumps 100 each.
select u.*, count(q.id), count(a.id) users u left join questions q on u.id = q.author_id left join answers on u.id = a.author_id group u.id
you need add distinct counts
select u.*, count(distinct q.id), count(distinct a.id) users u left join questions q on u.id = q.author_id left join answers on u.id = a.author_id group u.id here's demo of in action using data.se
alternatively can use inline views in clause
select u.*, q.questioncount, a.answercount users u left join (select count(id) questioncount, author_id questions group author_id) q on u.id = q.author_id left join (select count(id) answercount, author_id answers group author_id) on u.id = q.author_id
Comments
Post a Comment