Question

If I have two tables job, employee. I need to select all from job and append employee count for each job.

Supposed Result

job table
+-------------+-------------+
| id          | name        |
+-------------+-------------+
| 1           | Teacher     |
+-------------+-------------+
| 2           | Engineer    |
+-------------+-------------+
| 3           | Programmer  |
+-------------+-------------+

employee table
+-------------+-------------+-------------+
| id          | name        |   job_id    |
+-------------+-------------+-------------+
| 1           | employee N  |      1      |
+-------------+-------------+-------------+
| 2           | employee N  |      2      |
+-------------+-------------+-------------+
| 3           | employee N  |      3      |
+-------------+-------------+-------------+
| 4           | employee N  |      1      |
+-------------+-------------+-------------+
| 5           | employee N  |      3      |
+-------------+-------------+-------------+
| 6           | employee N  |      1      |
+-------------+-------------+-------------+

I need to select all from job and append employee count for each job.

Supposed Result

Result table
+-------------+-------------+--------------+
| id          | name        |employee count|
+-------------+-------------+--------------+
| 1           | Teacher     |      3       |
+-------------+-------------+--------------+
| 2           | Engineer    |      1       |
+-------------+-------------+--------------+
| 3           | Programmer  |      2       |
+-------------+-------------+--------------+
Was it helpful?

Solution

I like to use left join : )

SELECT job.id, job.name, count( * ) AS 'employee count'
FROM job
LEFT JOIN employee 
ON job.id = employee.job_id
GROUP BY job.id

OTHER TIPS

You want to use INNER JOIN to join the tables, then GROUP BY to group on the job id. Finally use COUNT() to get a count of each group

SELECT job.id, job.name, count(*) AS employee_count
FROM job
INNER JOIN employee 
  ON job.id = employee.job_id
GROUP BY job.id

You can see it live here http://sqlfiddle.com/#!2/9d59c1/1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top