簡體   English   中英

使用條件從另一個表中插入表記錄

[英]inserting into a table records from another table with a condition

假設我有兩個表 t1 和 t2。

  • t1 有兩個 integer cols col1 (primary) 和 col2
  • t2 有兩個 cols 一個外鍵 t1.col1 和 t2.col2

我想做以下

  1. 僅檢索 t1.col2 唯一的記錄,或者如果 t1.col2 重復,則僅檢索 t2.col2 不是 null 的記錄。

  2. 將上述記錄插入另一個匯總表,比如說 t3

這是我嘗試過的:

insert into t3 (col1,col2) 
    select col1, col2 
    from t1 
    where t.col1 in (select A.col1 from t1 as A 
                     group by 1 
                     having count(*) > 1
    union
    select col1, col2 
    from t1, t2 
    where t.col1 in (select A.col1 from t1 as A  
                     group by 1 
                     having count(*) > 1
      and t2.col2 is not null;

雖然 'union qry' 自己工作,但插入沒有發生。

請有任何想法或任何其他有效的方法來實現這一目標

您可以 select 您想要使用的記錄:

select t1.*
from (select t1.*, count(*) over (partition by col2) as cnt
      from t1
     ) t1 
where cnt = 1 or
      exists (select 1 from t2.col1 = t1.col1 and t2.col2 is null);

rest 只是一個insert

暫無
暫無

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

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