【问题标题】:Select only parent records when all children records meet conditions当所有子记录都满足条件时,只选择父记录
【发布时间】:2017-07-15 07:45:00
【问题描述】:

我有两个表 A 和 B,当所有子项(在表 B 中)都符合条件时,我只想要父 A 的行。如果 B 中的一行不符合条件,那么我不需要父 A 的行。我想我需要在这里使用exists,但不显示如何。

以下是数据表:

表A

Primary Key Level
1   low
2   low
3   high 
4   high 
5   low

表 B

Primary Key Phase   Parent Primary Key
1   open    1
2   open    1
3   close   1
4   close   2
5   close   2
6   close   3
7   open    4
8   open    4
9   open    5
10  close   5

我正在尝试的查询:

select * 
from table_a, table_b
where table_a.level = 'low' and
      table_b.phase = 'close' and
      table_a.primary_key=table_b.parent_primary_key

但我的查询也会返回 table_a.primary_key = 5 的行。

基本上,我想要返回的唯一行是 table_A.primary_key = 2 因为级别较低,并且两个子行的相位都等于关闭。

谢谢!

【问题讨论】:

  • 您是否尝试过 完全 那样,将单词 low 和 close 不包含在单引号中,但仍然得到结果?那甚至不应该编译(你应该得到一个“无效的标识符”错误)。
  • 不,抱歉,我在低位和收盘时有报价。我在尝试按原样发​​布时遇到问题。

标签: sql oracle exists


【解决方案1】:

这是你想要的吗

select a.*
from table_a a
where a.level = 'low' and
      not exists (select 1
                  from table_b b
                  where b.parent_primary_key = a.primary_key and
                        b.phase <> 'close'
                 );

not exists 是双重否定。它检查除了'close' 之外没有其他阶段的孩子——这基本上相当于说所有孩子都是'close'。 (如果允许NULL 值,则逻辑不完全等效。)

【讨论】:

  • 好的,非常感谢!那么你能帮忙解释一下 not exists 在这种情况下是如何工作的吗?
  • 我注意到你有'select a.*',有没有办法让输出包含两个表中的所有数据?
【解决方案2】:

或者:

select a.*
from table_a a
where a.level = 'low' and
      'close' = all (select phase
                  from table_b b
                  where b.parent_primary_key = a.primary_key
                 );

【讨论】:

  • 感谢您的帮助!这也是一个很好的选择
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-03
  • 2017-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-15
相关资源
最近更新 更多