我有以下表格。第一个表格的帖子带有类别表的外键。我正在寻找一个查询,该查询可为我提供每个类别的帖子数量。
帖子表。
select pstOccuId,pstTitle from job_post;
+-----------+-------------------------------------------+
| pstOccuId | pstTitle |
+-----------+-------------------------------------------+
| 1 | Software Engineer Recruit |
| 1 | Web Developer Recruit |
| 7 | Saxophonist |
| 5 | Construction Company looking for plumber. |
+-----------+-------------------------------------------+
类别表。
select occuDscr,occuId from occupation_field;
+---------------------+--------+
| occuDscr | occuId |
+---------------------+--------+
| Software Engineer | 1 |
| Economics | 2 |
| Structural Engineer | 3 |
| Legal Advisors | 4 |
| Plumbers | 5 |
| Social Advisors | 6 |
| Musicians | 7 |
+---------------------+--------+
我正在寻找一个能给我这样的查询。
+---------------------+--------+
| occuDscr | amount |
+---------------------+--------+
| Software Engineer | 2 |
| Plumbers | 1 |
| Musicians | 1 |
+---------------------+--------+
如果要显示包含 0 个帖子的类别,则需要使用
LEFT JOIN
而不是INNER
. 此外,对于除 mysql 之外的其他 RDMS,您必须GROUP BY a.occuId, a.occuDscr
(Mysql 让您只需GROUP BY a.occuId
由@RolandoMySQLDBA更新
@a1ex07 查询的输出如下所示:
这是您的样本数据:
这是结果:
要获取所有职业的计数,请按以下方式查询:
这是结果:
试试看 !!!
只是一个替代方案,您还可以执行以下查询,带来相同的结果。
SQL小提琴