如果我有两张桌子,雇员。 我需要从工作中选择所有工作并为每项工作追加员工人数。
假设结果
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 |
+-------------+-------------+-------------+
我需要从工作中选择所有工作并为每项工作追加员工人数。
假设结果
Result table
+-------------+-------------+--------------+
| id | name |employee count|
+-------------+-------------+--------------+
| 1 | Teacher | 3 |
+-------------+-------------+--------------+
| 2 | Engineer | 1 |
+-------------+-------------+--------------+
| 3 | Programmer | 2 |
+-------------+-------------+--------------+
答案 0 :(得分:2)
我喜欢使用左连接:)
SELECT job.id, job.name, count( * ) AS 'employee count'
FROM job
LEFT JOIN employee
ON job.id = employee.job_id
GROUP BY job.id
答案 1 :(得分:1)
您希望使用INNER JOIN
加入表格,然后使用GROUP BY
对作业ID进行分组。最后使用COUNT()
来计算每个组的数量
SELECT job.id, job.name, count(*) AS employee_count
FROM job
INNER JOIN employee
ON job.id = employee.job_id
GROUP BY job.id