[英]How to get a single record from main table and details about it from another table in a one:many relation?
作業(主表)
id | name | status
任務(詳細信息表)
id | result | job_id
PS:“結果”列可以將已delivered
, undelivered
或unknown
作為值
我想通過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';
我認為您的查詢有兩個問題:
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;
使用通用表表達式(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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.