[英]Update query using Subquery in PLSql Server
I compared table1 data table2 data, and filtered data which was not existed in table1.我比较了table1数据table2数据,过滤了table1中不存在的数据。 I want to make both tables rows count equal.
我想让两个表的行数相等。 For that, I need to set is_active = 0 in table2, where the data was not existed in table1.
为此,我需要在 table2 中设置 is_active = 0,其中 table1 中不存在数据。
Example::例子::
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'
In above example, table 1 and table2 contains similar data except 'M', 'N', 'O', I want set this row into is_active = 0 state.在上面的例子中,表 1 和表 2 包含类似的数据,除了 'M'、'N'、'O',我想将此行设置为 is_active = 0 状态。
To me, update with not exists seems to be one option.对我来说,不存在的更新似乎是一种选择。
Sample data:样本数据:
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
Update:更新:
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.
Result:结果:
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.