Reputation: 63
I have two tables in different databases (WAMP server) with the same structure. I want to copy from the first database (newkt
) to the second one (oldkt
) all rows that do not exist in the second database (oldkt
).
newkt -> table : users (1500 records) (id, name, password)
oldkt -> table : users (1200 records) (id, name, password)
I want to actually add rows to the oldkt
database whose id doesn’t exist in oldkt
yet.
Also if I have more than 3 columns, can these be added automatically or I do have to tag all of them?
Upvotes: 4
Views: 10551
Reputation: 13551
Disclaimer: Originally the OP tagged the question as both mysql and sql-server. I provided answer for both, leaving it at that as it is a more general solution than a purely MySQL one. When using MySQL, be sure to replace ..
in the query with .
.
SELECT … INTO table
does not work in MySQL (although it works in SQL Server) so INSERT … SELECT
will help you. It works in both MySQL and SQL Server.
You can specify table name including database name using .
(dot) delimiter in MySQL and ..
(double dot) delimiter in SQL Server. (See also a related question.)
EXCEPT
does not work in MySQL so instead we will use LEFT JOIN
and WHERE
. (See also a related question.)
For SQL Server:
INSERT INTO oldkt..users
SELECT newkt..users.*
FROM
newkt..users
LEFT JOIN oldkt..users USING(id)
WHERE
oldkt..users.id IS NULL
When used in MySQL, just replace the ..
with .
.
My solution works under the assumption that id
is unique key in both tables. (Primary key is always unique.) If this is not satisfied, the join condition must be adjusted to that fact.
Upvotes: 0
Reputation: 439
You can do like the following:
insert into database1.table select * from database2.table where id not in(select id from database1.table);
Upvotes: 10
Reputation: 416
Try the below code:
INSERT INTO TargetDatabase.dbo.TargetTable
SELECT * FROM SourceDatabase.dbo.SourceTable
EXCEPT
SELECT * FROM TargetDatabase.dbo.TargetTable
Upvotes: 0
Reputation: 4059
INSERT INTO oldkt
SELECT id , name ,password FROM newkt WHERE id NOT IN (SELECT id FROM oldkt )
Upvotes: 0
Reputation: 2775
As said you should be able to perform a typical insert but by specifying the database name in the query:
SELECT *
INTO TargetDatabase.dbo.TargetTable
FROM SourceDatabase.dbo.SourceTable
Upvotes: 0