sql - MySQL Join three tables return multiple results -
i have 3 tables: let's call customer, log , review
the customer table is:
id name == ==== 1 john 2 jane 3 mike
the log table is
id customer_id created_at == =========== ========== 1 1 2015-06-10 2 1 2015-06-10 3 2 2015-06-11 4 1 2015-06-13 5 2 2015-06-15 6 1 2015-06-15
the review table is
id customer_id created_at == =========== ========== 1 1 2015-06-10 2 2 2015-06-10 3 2 2015-06-11 4 1 2015-06-13 5 1 2015-06-15 6 1 2015-06-15 7 1 2015-06-18
what wanted
customer_id name log_qty review_qty =========== ==== ======= ========== 1 john 4 5 2 jane 2 2 3 mike 0 0
what got:
customer_id name log_qty review_qty =========== ==== ======= ========== 1 john 20 20 2 jane 4 4 3 mike 0 0
my query:
select customer.id, customer.name, count(review.customer_id) review_qty, count(log.customer_id) log_qty customer left join review on review.customer_id = customer.id left join log on log.customer_id = customer.id group customer.id order customer.id
if run query without count()
, group by
, you'll see what's happening:
select customer.id, customer.name, review.customer_id review_qty, log.customer_id log_qty customer left join review on review.customer_id = customer.id left join log on log.customer_id = customer.id order customer.id
this returns row each possible combination of rows same customer_id
3 tables (that's inner join
does). count
counts 'em!
this should give need:
select customer.id, customer.name, (select count(*) review customer_id = customer.id) review_qty, (select count(*) log customer_id = customer.id) log_qty customer order customer.id
Comments
Post a Comment