I have two tables t1 and t2. t1 has duplicated values. I need to insert all records from t1 to t2, but I don\'t want duplicates to occur in t2. I tried the following command whi
insert into test.t2(name2)
select distinct name1 from test.t1 where name1 NOT IN(select name2 from test.t2);
OR
insert into test.t2(name2)
select distinct name1 from test.t1 t1 where NOT EXISTS(select name2 from test.t2 t2 where t1.name1=t2.name2);
You've go two options here, one involves not duplicating the data on your insert, the second being to ignore duplicates when inserting.
To de-duplicate from the SELECT
call you'd use `DISTINCT:
INSERT INTO test.t2 (name2) SELECT name1 FROM test.t1 WHERE name1 NOT IN (SELECT name2 FROM test.t2)
You can also add a UNIQUE
index to avoid this problem in the first place:
ALTER TABLE t2 ADD UNIQUE INDEX index_name2 (name2)
Note that you will get an error if there is already duplicate data in t2
, so you may have to clean it up beforehand.
Then you can add data with the IGNORE
option:
INSERT IGNORE INTO test.t2 (name2) SELECT name1 FROM TEST.t1
The unique index approach will guarantee uniqueness.
I need to insert data from user to another user and when write this statement .....
insert into trep12.jobhead
select
*
from
wsfin04.jobhead
where
wsfin04.jobhead.job_no not in (select job_no from trep12.jobhead)
and wsfin04.jobhead.CHASS_NO not in (select CHASS_NO from trep12.jobhead)
and rdate between '01-jul-15'
and '01-oct-15'
and job_type = 1;
..... the result is 0 rows created.
this should do it:
INSERT IGNORE INTO test.t2 SELECT name2 FROM test.t1
Selects from one table and inserts into another.
You can create a unique index (of one or more columns) and then use the MySQL replace command.
CREATE UNIQUE INDEX unique_name2 ON t2 (name2);
REPLACE INTO t2 (name2) values ($name1);
...