我正在尝试在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
结果。
答案 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