0

I have three tables. a>b>c tables. I want to totals separately each other and optimize query. My query is not giving the true counts.

TABLE: a

a
-----------
id
no
create_time

TABLE: b

b
-----------
id
no

TABLE: c

c
-----------
id
b_id

this query is not giving the true counts

SELECT
    DATE( a.create_time ) AS date,
    COUNT( a.id ) AS total_a,
    COUNT( b.id ) AS total_b,
    COUNT( c.id ) AS total_c 
FROM
    `a`
    LEFT JOIN `b` ON `a`.`no` = `b`.`no`
    LEFT JOIN `c` ON `b`.`id` = `c`.`b_id` 
WHERE
    ( `a`.`status` = 1 ) 
GROUP BY
    DATE( a.create_time ) 
ORDER BY
    `date` DESC 
    LIMIT 20
3
  • Add Sample data and expected output Commented Mar 27, 2018 at 11:42
  • Try correlated sub-queries in the select list. Commented Mar 27, 2018 at 11:45
  • Thanks your answers, I solved with that Andomer's answer :) Commented May 14, 2018 at 6:09

1 Answer 1

3

A left join repeats each row on the left hand side for each matching row on the right hand side. So you get more rows than in the original.

An easy fix is to count just the unique identifiers:

SELECT
    DATE( a.create_time ) AS date,
    COUNT( DISTINCT a.id ) AS total_a,
    COUNT( DISTINCT b.id ) AS total_b,
    COUNT( DISTINCT c.id ) AS total_c 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.