如何从一个主表中获取一条记录,以及如何以一对多的关系从另一张表中获取有关该表的详细信息?

时间:2018-07-30 19:21:58

标签: sql postgresql

工作(主表)

id | name | status

任务(详细信息表)

id | result | job_id

PS:“结果”列可以包含deliveredundeliveredunknown作为值

我想通过id来获得一份工作,并在单行中按结果类型来获取有关它的详细信息,如下所示:

job_id | job_name | job_status | delivered | undelivered

我尝试了以下操作,但没有成功,因为我无法以这种方式使用作业列。有指针吗?

select jobs.id, jobs.name, jobs.status, sum(case when tasks.result = 
'deliverable' then 1 end) as deliverable,
sum(case when tasks.result = 'undeliverable' then 1 end) as 
undeliverable from jobs, tasks where jobs.id = 
tasks.job_id and jobs.id = 'We3dJzS4C1wysafM';

2 个答案:

答案 0 :(得分:0)

我认为您的查询有两个问题:

  • 不当使用表别名(jobs-> veb
  • group by

以下内容还修复了古老的join语法:

select v.id, v.name, v.status,
       sum( (t.result = 'deliverable')::int ) as deliverable,
       sum( (t.result = 'undeliverable')::int ) as undeliverable
from jobs v join
     tasks t
     on v.id = t.job_id and jobs.id = 'We3dJzS4C1wysafM'
group by v.id, v.name, v.status;

答案 1 :(得分:0)

使用公用表表达式(CTE)-

with deliverable_tasks as (
select t.job_id, count(*) as deliverable_count
from tasks t
where t.result='deliverable'
group by t.job_id
),
undeliverable_tasks as 
(
select t.job_id, count(*) as undeliverable_count
from tasks t
where t.result='undeliverable'
group by t.job_id
)
select
  j.id,
  j.name,
  j.status,
  dt.deliverable_count,
  ut.undeliverable_count
from jobs j
left join deliverable_tasks dt on dt.job_id=j.id
left join undeliverable_tasks ut on ut.job_id=j.id