0

I can not find where is the problem, my COUNT() returns the same number for both values contracts_count and records_count. When using only one of counts, everything works fine. Principle of this query: access company table, get it's id and name, company and group is related with foreign key in contract table, and record has foreign key related to group table. So I join company with contracts to get contracts count of each company and join group with contracts, records with group to get records count of each company.

SELECT 
`company`.`id`,
`company`.`name`,
COUNT(`contract`.`contract_id`) AS contracts_count, 
COUNT(`record`.`record_id`) AS records_count
                    FROM `company`
                    LEFT JOIN `contract`
                            ON `company`.`id`=`contract`.`fk_companystudijos_id`
                    LEFT JOIN `group` 
                            ON `contract`.`fk_groupID`=`group`.`id`
                    LEFT JOIN `record` 
                            ON `group`.`id`=`record`.`fk_groupID`
                            GROUP BY `company`.`id`
                            ORDER BY contracts_count DESC

1 Answer 1

1

COUNT() counts the number of rows with non-NULL values of its argument. That is pretty much the same for your two columns.

I'm pretty sure you want COUNT(DISTINCT):

COUNT(DISTINCT `contract`.`contract_id`) AS contracts_count, 
COUNT(DISTINCT `record`.`record_id`) AS records_count
Sign up to request clarification or add additional context in comments.

1 Comment

I have tried to use DISTINCT before, but I put it only on one COUNT(), thank you for the quick answer.

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.