Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two COUNTS with Left Joins are Being Multiplied

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`;
like image 536
carlbenson Avatar asked Jun 17 '11 04:06

carlbenson


People also ask

How does multiple LEFT join work?

The LEFT JOIN clause allows you to query data from multiple tables. The LEFT JOIN returns all rows from the left table and the matching rows from the right table. If no matching rows are found in the right table, NULL are used. In this syntax, T1 and T2 are the left and right tables, respectively.

Why the number of rows increase after left join?

There are two line items for ID 1003 in the second table, so the result of the join will be 2 line items. So, if your secondary tables have more than one row for the key you're joining with, then the result of the join will be multiple rows, resulting in more rows than the left table.

Does LEFT join change number of rows?

condition.

Can you use LEFT join twice?

Yes, indeed! You can use multiple LEFT JOINs in one query if needed for your analysis.


2 Answers

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.

like image 66
NullRef Avatar answered Nov 12 '22 00:11

NullRef


Your problem is likely that you're not mapping Place2User and Job2User tables, thus you are preforming a cross join. More info on Cross Joins

You will need to use inner queries to achieve this unless you the two tables Place2User relates to the Job2User in some way.

Try this:

SELECT `UserName`, `Job2User`.`Count`, `Place2User`.`Count` 
FROM `Users`
LEFT JOIN (SELECT `UserID`, COUNT(1) AS 'Count' FROM `Job2User` GROUP BY `UserID`) `Job2User` ON `Job2User`.`UserID`=`Users`.`UserID` 
LEFT JOIN (SELECT `UserID`, COUNT(1) AS 'Count' FROM `Place2User` GROUP BY `UserID`) `Place2User` ON `Place2User`.`UserID`=`Users`.`UserID` 
like image 24
Seph Avatar answered Nov 12 '22 00:11

Seph