0

Without the third join D.cid = C.id, this query gives me the count of C. With the third join it corrupts the count and gets unwanted tuples into the count of C's join. So how can I get the count of C and D without having the C count effected? Is there a form of parenthesis I can use to make sure I get the correct count?

SELECT A.*, B.*, COUNT(C.aid) AS cCount 
FROM tableA A

LEFT JOIN tableC AS C ON A.id = C.aid
INNER JOIN tableB AS B ON A.id = B.aid
LEFT JOIN tableD AS D ON D.cid = C.id

GROUP BY  A.id
1
  • There's COUNT(DISTINCT C.aid), unless you already expected to get duplicate c.aid's before you joined in table D. Commented Nov 15, 2011 at 4:03

1 Answer 1

1

I would have the counts from the other tables pre-aggregated unto themselves and joined... something like...

SELECT 
      A.*, 
      B.*, 
      COALESCE( PreAggC.CCount, 0 ) as CCount,
      COALESCE( PreAggC.WithDCount, 0 ) as WithDCount
   FROM 
      tableA A

         JOIN tableB B
            on A.ID = B.aID

         LEFT JOIN ( select aID, 
                            count( distinct id ) CCount,
                            count(*) as WithDCount
                        from tableC
                           left join tableD D
                              on c.ID = D.cID
                        group by aID ) PreAggC
            on A.id = PreAggC.aID

Now, do you really want how many entries actually have "D" records? so I included both counts... distinct "C" entries, and the overall count with correlation with "D"

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.