I have two tables, users and departments. I want to have table, where are two columns: first is department name, second is count - how many users are assigned to this department. And I have this piece of code:
SELECT department_name as 'deptName',
COUNT(users.department_id) as 'userCount'
FROM departments
LEFT OUTER JOIN users
ON departments.id = users.department_id
GROUP BY 'deptName'
Department's table columns are:
integer id PK
varchar(20) department_name
User's table columns are:
integer id PK
varchar(20) name
varchar(20) surname
int department_id FK
But it does not work.
Now I have 2 departments, and output should be 2 rows, first with count 8 and second with count 1. But I see only one row, with all count (9). I use MySQL installed with XAMPP.
An SQL expert explains how using a LEFT OUTER JOIN query can retrieve zero row counts in SQL.
To achieve this for multiple tables, use the UNION ALL. select sum(variableName. aliasName) from ( select count(*) as yourAliasName from yourTableName1 UNION ALL select count(*) as yourAliasName from yourTableName2 ) yourVariableName; Let us implement the above syntax.
Left Outer Join: Left Outer Join returns all the rows from the table on the left and columns of the table on the right is null padded. Left Outer Join retrieves all the rows from both the tables that satisfy the join condition along with the unmatched rows of the left table. SELECT [column1, column2, ....]
A left outer join is a method of combining tables. The result includes unmatched rows from only the table that is specified before the LEFT OUTER JOIN clause. If you are joining two tables and want the result set to include unmatched rows from only one table, use a LEFT OUTER JOIN clause or a RIGHT OUTER JOIN clause.
SELECT department_name as 'deptName',
COUNT(users.department_id) as 'userCount'
FROM departments
LEFT OUTER JOIN users
ON departments.id = users.department_id
GROUP BY `deptName`
Notice the tick marks vs. your single quotes in the GROUP BY (this is the key to the left of the 1 on your keyboard). Refer to: http://dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html
You could also just group by department_name (the field itself, rather than the alias)
Currently you are grouping on the literal value 'deptName', not the field that you've given an alias of deptName, which is why you only have 1 row returned. You're not actually doing any grouping.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With