MySQL内部连接另一个表的计数

时间:2014-07-03 15:31:10

标签: php mysql

我正在尝试在MySQL中执行SELECT查询,该查询还会在另一个表格中执行count,并join将答案放入我的初始table

people

id |名字| hair_color | JOB_ID

job

id | job_name

SELECT * 
FROM job j
INNER JOIN (SELECT COUNT(job_id) AS totals
           FROM people p
           WHERE p.job_id='1')
     ON j.count = totals
WHERE id = '1'
ORDER BY id ASC

所以我试图通过job从我的id表中选择上面的查询,并在count表中执行people并添加列count我的job结果。

1 个答案:

答案 0 :(得分:5)

您不必在子查询中进行计数:您可以直接选择计数然后分组。此外,您不必手动精确people job_id:在两个表字段之间直接进行JOIN(最少)。

SELECT j.id, j.job_name, count(p.id) as nb_people
  FROM job j
       INNER JOIN people p ON p.job_id = j.id
 WHERE j.id = '1'
GROUP BY j.id, j.job_name
ORDER BY id ASC

查看MySQL聚合函数文档:http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html

或许可以再看一下JOIN文档:http://dev.mysql.com/doc/refman/5.7/en/join.html