当所有孩子共享相同的值时查找父母ID [英] Find parent id when all children share the same value
问题描述
我有一些看起来像这样的数据
I have some data that looks a little like this
Table C
id | end_time
-------------
1 '2019-01-01'
2 '2020-01-01'
3 '2019-07-01'
Table F
id | parent_id
12 | 1
13 | 1
21 | 2
22 | 2
31 | 3
32 | 3
33 | 3
34 | 3
Table oui
rel_id | Product Version
1 '2'
12 '2'
13 '1'
2 '1'
21 '2'
22 '1'
3 '2'
31 '1'
32 '1'
33 '1'
34 '1'
数据关系:
c.id = f.parent_id
Data relationship: c.id = f.parent_id
c.id或f.id = oui.rel_id
c.id or f.id = oui.rel_id
我要查找的是表oui中C的rel_id在哪里父级的产品版本为2,但所有子级的版本均为1。
What I'm trying to find is where the rel_id for C in table oui is the parent's product version is 2, but ALL children are version 1.
我在此处发现了类似的问题:查找所有孩子完全匹配的父母的ID ,但不能完全适应此用例。
I found a similar question over here: Find ID of parent where all children exactly match but couldn't quite adapt it to this use case.
预期结果:
c.id
----
3
原因:两个c.id 1/2都有至少有1个孩子的孩子它em在产品版本2中。
Reasoning: Both c.id 1/2 have children which have at least 1 item in product version 2.
推荐答案
尝试一下:
select
t1.id
from c "t1"
inner join oui "t2" on t2.rel_id=t1.id
where t2.product_version='2' -- product_version for Parent
and
(select
count(*)
from f "t3"
inner join oui t4 on t4.rel_id=t3.id
where t4.product_version !='1' -- product_version for Child
and t3.parent_id=t1.id
)=0
注意:如果表<$中的 ID
,上述查询将非常有效表 F
中的c $ c> C 和 ID
不相同,而<$ c表 oui
中的$ c> rel_id 列具有唯一值。
Note: Above query will work perfectly if the ID
in table C
and ID
in table F
is not same and rel_id
column in table oui
is having unique values.
这篇关于当所有孩子共享相同的值时查找父母ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!