簡體   English   中英

在復合鍵中搜索缺失或重復的值

[英]Searching for missing or duplicated values in composite keys

假設我有一個包含兩部分復合鍵的表,如下所示:

Key1  Key2  
a     char1  
a     char2  
a     char3  
a     char4  
a     char5
b     char1 
etc.

我需要檢查是否存在 Key1 的值,其中缺少或重復來自 Key2 的對應值(即來自 key1 的值沒有來自 key2 的 5 個特定值)。 我是 sql 的新手,在此先感謝您的幫助。

樣本數據:

SQL> select * From test order by key1, key2;

KEY1 KEY2
---- ----
a    ch1
a    ch2
a    ch3
b    ch1
c    ch2
c    ch3

6 rows selected.

一種選擇是

  • 創建所有[KEY1, KEY2]組合的交叉連接
  • 使用MINUS集合運算符,在源表中查找缺失值

SQL> with
  2  -- distinct keys
  3  k1 as (select distinct key1 from test),
  4  k2 as (select distinct key2 from test),
  5  -- cross join makes all possible combinations
  6  cj as
  7    (select a.key1, b.key2
  8     from k1 a cross join k2 b
  9    )
 10  -- MINUS set operator returns missing key combinations
 11  select key1, key2 from cj
 12  minus
 13  select key1, key2 from test;

KEY1 KEY2
---- ----
b    ch2
b    ch3
c    ch1

SQL>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM