如何使用 table employee in mysql query 的 column position 获取 table job position 的职位空缺数量?

How to get number of job vacancies in table job position using the column position in table employee in mysql query?

我有table职位和员工

tbl_job_position:

job_id, job_description, job_quantity(number of max vacant)

1     Programmer        3
2     Accountant        2
3     Driver            3
4     HR Officer        2

tbl_employee:

emp_id, emp_pos_id 
1       1
2       1
3       2
4       3
5       3
6       3

我想创建一份报告:

job_position, no_of_active_emp, no_of_vacancies
   Programmer        2                 1
   Accountant        1                 1
   Driver            3                 0
   HR Officer        0                 2

如何在 mysql 中查询?任何帮助将不胜感激,谢谢。

查询-

select job_description, cnt as no_of_active_emp, 
job_quantity - e.cnt as no_of_vacancies
from tbl_job_position p, 
(select e.emp_pos_id, count(*) cnt
from tbl_employee e
group by e.emp_pos_id) e
where p.job_id = e.emp_pos_id

DB fiddle here

为了显示未分配给员工的工作职位,我们 select 所有来自 job_position table 和 select 仅来自空缺 table 的匹配记录这是左连接。

select job_description, COALESCE(cnt,0) as no_of_active_emp,
job_quantity - COALESCE(e.cnt,0) as no_of_vacancies
from tbl_job_position p left join
(select e.emp_pos_id, count(*) cnt
from tbl_employee e
group by e.emp_pos_id) e
on p.job_id = e.emp_pos_id

DB fiddle here