MySQL Join和COUNT(*)查询

时间:2014-10-05 22:42:51

标签: mysql database

我有问题。解决了我缺乏SQL知识的问题。 我有2张桌子。

Table : Jobs
+---+----------+
|ID | JobName  |
+---+----------+
| 1 | Tinker   |
| 2 | Tailor   |
| 3 | Soldier  |
| 4 | Sailor   |
+---+----------+

Table : Applied
+---+--------------+--------+
|ID | JobAppliedID | Name   |
+---+--------------+--------+
|1  | 1            |Cliff   |
|2  | 2            |John    |
|3  | 2            |Ringo   |
|4  | 2            |Paul    |
+---+--------------+--------+

现在,我要做的是创建一个只在表JOBS上执行简单SELECT的SQL,...

SELECT * FROM Jobs;

但我想在SELECT中重新计算每个作业申请的次数。例如,它将返回以下内容。

+---+----------+-------+
|ID | JobName  | Count |
+---+----------+-------+
| 1 | Tinker   |   1   |
| 2 | Tailor   |   3   |
| 3 | Soldier  |   0   |
| 4 | Sailor   |   0   |
+---+----------+-------+

我想我需要一个嵌入式SELECT,但我不知道从哪里开始。

有人可以帮忙吗?

感谢。

1 个答案:

答案 0 :(得分:3)

你需要像这样的左连接...使用coalesce来处理空值

SELECT j.*, COUNT(a.jobappliedid) AS numApplied
FROM jobs j
LEFT JOIN applied a ON a.jobappliedid = j.ID
GROUP BY j.id

Fiddle Demo