sql - compare rows between two ids with in the same table and insert the missing row for that id
问题描述
i have a table which has structure mentioned below let's say table name -> tab1
id c1 c2 c3 c4
1 a b 01-02-18 c row1
1 o b 01-02-18 c row2
1 a b 04-05-16 c row3
1 n g 01-02-18 d row4
2 a b 01-02-18 c row5
So i want to insert id 1 rows to id 2. As data for row1 and row5 is same for column c1,c2,c3,c4 so i want to skip row1 to be inserted for id 2 .
Table should look like this
id c1 c2 c3 c4
1 a b 01-02-18 c row1
1 o b 01-02-18 c row2
1 a b 04-05-16 c row3
1 n g 01-02-18 d row4
2 a b 01-02-18 c row5
2 o b 01-02-18 c row6
2 a b 04-05-16 c row7
2 n g 01-02-18 d row8
i have written this query but doesn't give me the expected result
for selecting the unique record based on column :
select Count(*) FROM tab1 A
WHERE Not EXISTS
(select * from tab1 B where A.c1 = B.c1 AND A.c2 = B.c2 AND A.c3= B.c3
AND A.c4 = B.c4
and B.id=2 )and A.id = 1;
for inserting the records
insert into rsk_mdl_sec_map_ts
select '2', c1, c2, c3, c4
FROM tab1 A
WHERE Not EXISTS
(select * from tab1 B where A.c1 = B.c1 AND A.c2 = B.c2 AND A.c3= B.c3
AND A.c4 = B.c4
and B.id=2 )and A.id = 1;
can anyone help what is wrong in this or suggest me some other approach to achieve the same . Thanks
解决方案
首先构建一个查询,选择应该插入的行并忽略那些已经存在的行id=2
:
SELECT *
FROM tab1 t1
WHERE id = 1
AND NOT EXISTS (
SELECT 'anything' FROM tab1 t2
WHERE t1.c1=t2.c1
AND t1.c2=t2.c2
AND t1.c3=t2.c3
AND t1.c4=t2.c4
AND id = 2
)
| ID | C1 | C2 | C3 | C4 |
|----|----|----|-----------------------|----|
| 1 | o | b | 2018-01-02 00:00:00.0 | c |
| 1 | a | b | 2016-04-05 00:00:00.0 | c |
| 1 | n | g | 2018-01-02 00:00:00.0 | d |
演示:http ://sqlfiddle.com/#!4/d66fc/4
接下来,使用 INSERT ... SELECT .... 命令,只需将 INSERT 放在 SELECT 命令上方,并使用2
常量作为 ID,并使用 DISTINCT 子句删除可能的重复项:
INSERT into tab1( id, c1, c2, c3, c4 )
SELECT DISTINCT 2, c1, c2, c3, c4
FROM tab1 t1
WHERE id = 1
AND NOT EXISTS (
SELECT 'anything' FROM tab1 t2
WHERE t1.c1=t2.c1
AND t1.c2=t2.c2
AND t1.c3=t2.c3
AND t1.c4=t2.c4
AND id = 2
)
推荐阅读
- css - 选中复选框时设置元素样式
- mongodb - 在 MongoDB 中的数组的相同元素中查找 2 个或多个条件
- java - Spring Cloud Stream 绑定可视化
- ios - 下载PDF文件并保存在文档目录中
- dart - 拖动时页面视图“跳跃”
- methods - 如何将返回值从一种方法传递给另一种方法?
- javascript - 垂直滚动不适用于表格
- oracle - 如何在 oracle 中将 pls_number 转换为 varchar2?
- python - 在外部 Docker 镜像中构建 python 的 gevent
- contao - 404 页面生成问题新闻类别过滤 - Contao