簡體   English   中英

在 PLSql Server 中使用子查詢更新查詢

[英]Update query using Subquery in PLSql Server

我比較了table1數據table2數據,過濾了table1中不存在的數據。 我想讓兩個表的行數相等。 為此,我需要在 table2 中設置 is_active = 0,其中 table1 中不存在數據。

例子::

UPDATE table2 
SET table2.is_active = 0 
WHERE (SELECT table2.user_name 
       FROM table2 
       WHERE table2.is_Active = 1 
         AND table2.user_name NOT IN (SELECT table1.user_name 
                                      FROM table1 
                                      WHERE table1.is_Active = 1));
==table1==      ==table2==
'A', 'B', 'C'   'A', 'B', 'C'
'A', 'E', 'C'   'M', 'N', 'O'
'A', 'E', 'D'   'A', 'E', 'D'
                'A', 'E', 'D'

在上面的例子中,表 1 和表 2 包含類似的數據,除了 'M'、'N'、'O',我想將此行設置為 is_active = 0 狀態。

對我來說,不存在的更新似乎是一種選擇。

樣本數據:

SQL> select * from table1;

COL1  COL2  COL3   IS_ACTIVE
----- ----- ----- ----------
a     b     c              1
a     e     c              1
a     e     d              1

SQL> select * from table2;

COL1  COL2  COL3   IS_ACTIVE
----- ----- ----- ----------
a     b     c              1
a     e     c              1
a     e     d              1
m     n     o              1   --> IS_ACTIVE should be set to 0

更新:

SQL> update table2 b set
  2    b.is_active = 0
  3    where not exists (select null from table1 a
  4                      where a.col1 = b.col1
  5                        and a.col2 = b.col2
  6                        and a.col3 = b.col3
  7                     );

1 row updated.

結果:

SQL> select * from table2;

COL1  COL2  COL3   IS_ACTIVE
----- ----- ----- ----------
a     b     c              1
a     e     c              1
a     e     d              1
m     n     o              0   --> IS_ACTIVE is set to 0

SQL>

暫無
暫無

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

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