连接两个表,其中一个表包含多行,这些行引用另一表 PSQL 中的一行
Posted
技术标签:
【中文标题】连接两个表,其中一个表包含多行,这些行引用另一表 PSQL 中的一行【英文标题】:Joining two tables where one contains multiple rows that refer to one row in the other table PSQL 【发布时间】:2018-01-11 12:17:29 【问题描述】:所以我有两个看起来像这样的表:
nalog
:
prod_num
id
qa_stavka_kontrola
:
status
id_nalog
id
redak --question id
第二个表用于存储关于第一个表中包含的书籍的是或否答案(在列 status(boolean) 中)。第二个表的多行是指第一个表中的一行。我想做一个看起来像这样的报告:
|prod_num | question 1 | question 2 | question 3 |
|52 | 1 | 0 | 1 |
|53 | 0 | 1 | 1 |
这是我的查询,但速度非常慢:
select nalog.prod_num
, r1.status as question1
, r2.status as question2
, r3.status as question3
from nalog
left join qa_stavka_kontrola as r1
on nalog.id=r1.id_nalog and r1.redak=1 and (r1.status=1 or r1.status=0)
left join qa_stavka_kontrola as r2
on nalog.id=r2.id_nalog and r2.redak=2 and (r2.status=1 or r2.status=0)
left join qa_stavka_kontrola as r3
on nalog.id=r3.id_nalog and r3.redak=3 and (r3.status=1 or3.status=0)
where nalog.date BETWEEN '2017-09-01' and '2018-01-11'
group by nalog.prod_num, r1.status, r2.status, r3.status
【问题讨论】:
所以最多三个问题? qa_stavka_kontrola 中的每个 id_nalog 和 redak 不能有多个条目? 【参考方案1】:我可能会离开,但您可以尝试使用 PIVOT,查看文档了解更多信息。
with something as
(select t1.prod_num, t2.redak
from nalog t1
left outer join qa_stavka_kontrola t2
on t1.id=t2.id_nalog
where t2.status in (0,1)
and t1.date BETWEEN '2017-09-01' and '2018-01-11' -- is there a date column?
)
select *
from something
pivot (count(redak) for redak in (1 as question_1, 2 as question_2, 3 as question_3));
【讨论】:
以上是关于连接两个表,其中一个表包含多行,这些行引用另一表 PSQL 中的一行的主要内容,如果未能解决你的问题,请参考以下文章