Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL COUNT() function and LEFT OUTER JOIN

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.

like image 278
Radek Anuszewski Avatar asked Sep 07 '14 15:09

Radek Anuszewski


People also ask

What will be the row count if you do left outer join?

An SQL expert explains how using a LEFT OUTER JOIN query can retrieve zero row counts in SQL.

How do I join two tables and 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.

How can I check left outer join?

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, ....]

What is the function of a left outer join in SQL?

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.


1 Answers

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.

like image 103
Brian DeMilia Avatar answered Sep 25 '22 06:09

Brian DeMilia