A表:
id name
1 aa
2 bb
1 ss
B表 :
id name
1 aa
3 cc
1 dd
A B 两个字段都不重复才不是重复数据
inset into B (id,name)
select id , name from A
这个语句怎样写 插入数据不重复
------解决方案--------------------
如果是表中无数据,可以针对这两个字段加上两个字段的唯一性索引,如果有数据可以用merge
Merge Into a
Using (Select b.* From b) o
On (o.Id = a.Id And o.Name = b.Name)
When Not Matched Insert Into(b.Id, b.Name);
------解决方案--------------------
/*
DROP TABLE a;
DROP TABLE b;
CREATE TABLE a(ID NUMBER,NAME VARCHAR2(20));
CREATE TABLE b(ID NUMBER,NAME VARCHAR2(20));
insert into a values(1,'aa');
insert into a values(2,'bb');
insert into a values(1,'ss');
insert into b values(1,'aa');
insert into b values(3,'cc');
insert into b values(1,'dd');
COMMIT;
SELECT * FROM A;
SELECT * FROM B;
*/
--方法1
INSERT INTO A
SELECT B.ID, B.NAME
FROM B
WHERE NOT EXISTS (SELECT 1
FROM A
WHERE A.ID = B.ID
AND A.NAME = B.NAME);
--方法2
INSERT INTO A
SELECT B.* FROM B
MINUS
SELECT B.ID,B.NAME FROM A,B WHERE A.ID = B.ID AND A.NAME = B.NAME;
--方法3
MERGE INTO A
USING B
ON(A.ID = B.ID AND A.NAME = B.NAME)
WHEN NOT MATCHED THEN
INSERT VALUES(B.ID,B.NAME);
--方法4
DECLARE
N_NUM NUMBER(2);
BEGIN
FOR I IN (SELECT * FROM B) LOOP
SELECT COUNT(1) INTO N_NUM FROM A WHERE A.ID = I.ID AND A.NAME = I.NAME;
IF N_NUM<1 THEN
INSERT INTO A VALUES(I.ID,I.NAME);
END IF;
END LOOP;
END;
--方法5
CREATE TABLE A_COPY AS
SELECT A.ID,A.NAME FROM A
UNION
SELECT B.ID,B.NAME FROM B;
ALTER TABLE A_COPY RENAME TO AA;