Aarushi
Aarushi

Reputation: 564

Where clause in Insert command in mysql

I need to do something like this

insert into tableA(code) select code from tableB where id=tableB.id;

I cant insert the code until both id are matched. How do i do this?

Upvotes: 0

Views: 30

Answers (2)

Vipin Jain
Vipin Jain

Reputation: 3756

INSERT INTO tableA.field1,tableA.field2,......
SELECT tableB.field1,tableB.field2,......
FROM tableB  
JOIN tableA ON tableA.id = tableB.id;

Upvotes: 0

Rahul
Rahul

Reputation: 77926

You can either do a join or use where exists like

insert into tableA(code) 
select tb.code 
from tableB tb 
join tableA on tableA.id = tableB.id;

(OR)

insert into tableA(code) 
select tb.code 
from tableB tb where exists(select 1 from tableA 
where id = tb.id);

Looking at your comment, looks like you rather need a UPDATE statement like

UPDATE tableA a 
    JOIN tableB b ON a.id = b.id 
SET a.code = b.code;

Upvotes: 1

Related Questions