我有两张桌子:
t_job
- id
- name
t_person:
- id
- name
- job_id (fk t_job->id)
t_other_jobs
- person_id (fk t_person->id)
- job_id (fk t_job->id)
所以基本上我有人有主要工作和0个或更多的二级工作。 我想要做的是创建查询,给我这样的东西:
PERSON NAME | ALL JOBS COUNT
和
JOB NAME | HOW MANY PEOPLE HAVE THEM
因此,如果一个人有主要工作(它是一个外键,所以他必须拥有它)和另外两个工作。结果将是:
Jorge | 3
答案 0 :(得分:2)
既然你说他们总是有工作,你可以算上他们的其他工作并加1:
SELECT
p.id,
p.name,
count(o.job_id)+1 as Jobs
FROM
t_person p
LEFT JOIN
t_other_jobs o
ON
p.id=o.person_id
GROUP BY
p.id, p.name;
答案 1 :(得分:0)
这个qwery会给你第一个结果。
select
person.id,
count(distinct (person.job_id)) + count(other_jobs.job_id) as All_job
from
person
Inner JOin
other_jobs
where
person.id = other_job.person_id
group by person.id
这将为您提供第二个。
select
job.name, count(distinct (person.id)) as no_of_people
from
person
INNER JOIN
job ON person.job_id = job.id
group by job_id
UNION select
job.name, count(distinct (person_id)) as no_of_people
from
other_job
INNER join
job ON job.id = other_job.job_id
group by job_id;
答案 2 :(得分:0)
尝试
第一次查询(PERSON NAME | ALL JOBS COUNT
)
SELECT name PersonName, maincount + Count(o.Job_Id) AS AllJobsCount
FROM (
SELECT p.Id, p.name, COUNT(m.Id) AS MainCount
FROM t_person p
LEFT JOIN t_job m ON p.job_id = m.Id
GROUP BY P.Id
) a
Left Join t_other_jobs o ON A.Id = o.person_id
GROUP BY a.Id
第二次查询(JOB NAME | HOW MANY PEOPLE HAVE THEM
)
SELECT j.Name JobName,
(SELECT COUNT(1) FROM t_person WHERE job_id=j.Id) +
(SELECT COUNT(1) FROM t_other_jobs WHERE job_id=j.Id) AS Count
FROM t_job j