I am trying to get a query that gives me the UserNames from table Users, the number of Jobs that user has from table Job2User, and the number of Places that user has from the table Place2User.
The following query keeps multiplying the value of the two count columns. For example, if for User 1 the Jobs count should be 2 and the Places count should be 4, both columns in the User 1 row will display “8”. I’m not sure what I’m doing wrong:
SELECT `UserName`, COUNT(`Job2User`.`UserID`), COUNT(`Place2User`.`UserID`)
FROM `Users`
LEFT JOIN `Job2User` ON `Job2User`.`UserID`=`Users`.`UserID`
LEFT JOIN `Place2User` ON `Place2User`.`UserID`=`Users`.`UserID`
GROUP BY `UserName`;
You should use
count( distinct ...)to count unique values. Instead of counting userid ( the foreign key) count the referenced table’s primary key.See the docs here
You are getting eight because you are returning 2 records from jobs and 4 from places. Since you are not counting distinct values you get 2*4 = 8.