[英]Insert rows based on another row
我的表格中有一行,如果其他相似的行不存在,则需要插入它们。 例如,列SubKey1 = XFITEST和列SubKey2 =5。我需要检查是否有行,其中列SubKey1 = XFITEST和列SubKey2 = 7,否则,我需要将其插入。 基本上,我需要检查每个具有Subkey2 = 5的SubKey1,并确保它也具有具有相同SubKey1但SubKey2 = 7的行,如果不是,则需要插入它。
谢谢!
编辑:希望是一个很好的例子。 在下面的示例中,我需要确定Subkey1 XFITEST缺少subkey2为7的行并将其插入。
这就是我目前所拥有的。 我需要检查Subkey1中有一堆不同的值。
SubKey1 SubKey2
AISBTF500 5
AISBTF500 7
XFITEST 5
这就是我想要完成的。
SubKey1 SubKey2
AISBTF500 5
AISBTF500 7
XFITEST 5
XFITEST 7
您可以像下面这样:
insert into Table1(SubKey1, SubKey2)
select SubKey1, 7 as SubKey2 from Table1 as tbl1
where SubKey2=5 and
not exists(select 1 from Table1 where SubKey1=tbl1.SubKey1 and SubKey2=7)
group by SubKey1, SubKey2
您可以将not exists
insert into .... select
中使用它。
在得到SubKey1
它不具有SubKey2 = 7
名。 然后将其插入。
create table t(
SubKey1 varchar(50),
SubKey2 int
);
insert into t values ('AISBTF500',5);
insert into t values ('AISBTF500',7);
insert into t values ('XFITEST',5);
INSERT INTO T (SubKey1,SubKey2)
SELECT SubKey1,7
FROM T t1
WHERE not exists (
SELECT 1
FROM T tt
WHERE tt.SubKey2 = 7 and tt.SubKey1 = t1.SubKey1
)
查询1 :
select * from t
结果 :
| SubKey1 | SubKey2 |
|-----------|---------|
| AISBTF500 | 5 |
| AISBTF500 | 7 |
| XFITEST | 5 |
| XFITEST | 7 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.