【发布时间】:2021-09-09 03:49:21
【问题描述】:
我有一个带有 3 个表的 MySQL 5.6 数据库:
job_offer
+----+----------+-------------+-----------+
| id | name | position_id | status_id |
+----+----------+-------------+-----------+
| 1 | John | 1 | 4 |
| 2 | Smith | 1 | 4 |
| 3 | Williams | 2 | 2 |
+----+----------+-------------+-----------+
位置
+----+----------+
| id | name |
+----+----------+
| 1 | frontend |
| 2 | backend |
+----+----------+
状态
+----+-----------+
| id | name |
+----+-----------+
| 1 | contacted |
| 2 | declined |
| 3 | rejected |
| 4 | interview |
+----+-----------+
我想构建一个查询,可以按职位和状态计算所有工作机会。 我有这个查询几乎按照我想要的方式执行:
SELECT
position.name AS position_name,
status.name AS status_name
COUNT(job_offer.id) AS offers
FROM
job_offer
LEFT OUTER JOIN
position
ON job_offer.position_id = position.id
LEFT OUTER JOIN
status
ON job_offer.status_id = status.id
GROUP BY
position_name, status_name
这给了我这个结果:
+---------------+-------------+--------+
| position_name | status_name | offers |
+---------------+-------------+--------+
| frontend | interview | 2 |
| backend | declined | 1 |
+---------------+-------------+--------+
唯一的问题是我还需要显示与职位相关的所有现有状态,无论是否为 NULL。所以理想情况下它应该是这样的:
+---------------+-------------+--------+
| position_name | status_name | offers |
+---------------+-------------+--------+
| frontend | contacted | 0 |
| frontend | declined | 0 |
| frontend | rejected | 0 |
| frontend | interview | 2 |
| backend | contacted | 0 |
| backend | declined | 1 |
| backend | rejected | 0 |
| backend | interview | 0 |
+---------------+-------------+--------+
是否有可能通过一个查询来实现?提前感谢您的帮助。
【问题讨论】: