gpt4 book ai didi

sql - 多对一关系,只选择祖先满足所有条件的行

转载 作者:行者123 更新时间:2023-11-29 11:45:38 26 4
gpt4 key购买 nike

首先我将向您展示表的架构。

 Table "public.questionare"
Column | Type |
--------------------+-----------------------+
id | integer |




Table "public.questionareacceptance"
Column | Type |
-------------------------+-----------------------+
id | integer |
questionare_id | integer |
accept_id | integer |
impact_id | integer |

questionareacceptance 包含:

id  | questionare_id | accept_id|       impact_id  |
----+----------------+----------+------------------+
1 |1 |1 | |
2 |1 |1 | 1 |
3 |1 |1 | 1 |
4 |2 | | 1 |
5 |3 |1 | 1 |
6 |4 |1 | 1 |
7 |4 |1 | 1 |

我想要得到的是一个 questionare ID 列表,其中每个 questionareacceptance 字段 accept_idimpact_id 不是 NULL

我的查询如下:

SELECT q.id AS quest,
qa.id AS accepted
FROM questionare q,
questionareacceptance qa
WHERE q.id = qa.questionare_id
AND qa.accept_id IS NOT NULL
AND qa.impact_id IS NOT NULL;

但结果是休闲的:

      quest         |          accepted     |                           
--------------------+-----------------------+
1 |1 |
1 |2 |
1 |3 |
2 |4 |
3 |5 |
4 |6 |
4 |7 |

但应该返回的结果只有34,其他的impact_idaccept_id为null。

谁能指出我哪里做错了?

最佳答案

您的查询可以写成不存在:

select
q.id as quest, qa.id as accepted
from questionare as q
inner join questionareacceptance as qa on qa.questionare_id = q.id
where
not exists (
select *
from questionareacceptance as tqa
where
tqa.questionare_id = q.id and
(tqa.accept_id is null or tqa.impact_id is null)
)

但我认为使用窗口函数会更快:

with cte as (
select
q.id as quest, qa.id as accepted,
sum(case when qa.accept_id is not null and qa.impact_id is not null then 1 else 0 end) over(partition by q.id) as cnt1,
count(*) over(partition by q.id) as cnt2
from questionare as q
inner join questionareacceptance as qa on qa.questionare_id = q.id
)
select quest, accepted
from cte
where cnt1 = cnt2

实际上看起来你根本不需要加入:

with cte as (
select
qa.questionare_id as quest, qa.id as accepted,
sum(case when qa.accept_id is not null and qa.impact_id is not null then 1 else 0 end) over(partition by qa.questionare_id) as cnt1,
count(*) over(partition by qa.questionare_id) as cnt2
from questionareacceptance as qa
)
select quest, accepted
from cte
where cnt1 = cnt2;

sql fiddle demo

关于sql - 多对一关系,只选择祖先满足所有条件的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19222051/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com