2

我有 2 张桌子:

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

因此,如果一个人有主要工作(它是一个外键,所以他必须拥有它)和其他 2 个工作。结果将是:

Jorge | 3
4

3 回答 3

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;
于 2013-04-16T06:46:51.147 回答
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;
于 2013-04-16T07:52:57.213 回答
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
于 2013-04-16T09:13:34.277 回答