0

I am trying to get this seemingly simple looking query to work :

SELECT
c.id,
c.name,
count(chc.id) as contacts_count,
count(cha.id) as addresses_count

FROM
(customers c LEFT JOIN customer_has_contacts chc on c.id = chc.customer_id) 
    LEFT JOIN customer_has_addresses cha on c.id = cha.customer_id

WHERE
c.company_id = ?

GROUP BY
c.id

But I keep getting the following result. I do not know where I am going wrong :

enter image description here

  • 1
    And what is the problem with the result? 24 is not correct I should guess? If yes, you need count(distinct chc.id) and count(distinct cha.id). See this similar question: dba.stackexchange.com/questions/17012/help-with-this-query – ypercubeᵀᴹ Oct 16 '15 at 19:21
  • @ypercube wow. yes. that gave me the correct result. There weren't even 24 rows in each of those tables. – Yash Desai Oct 16 '15 at 19:27
  • Yes, there were either 3 and 8 (or 4 and 6, or 2 and 12, or 1 and 24 ;). – ypercubeᵀᴹ Oct 16 '15 at 19:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.