0

I have a Database (MySQL) that contains two tables with identical primary keys, I have already inserted data into the first table but I want to insert data into the second table at a later time.

The logic I've got is:

[INSERT into Table2 (col1, col2, col3) Values (X1,X2,X3)  WHERE Table1.id equals Table2.id] 

I can't seem to find anything that works like this for an Insert Statement in use with PHP.

Any help appreciated!

winhowes
  • 7,845
  • 5
  • 28
  • 39
Charles
  • 1
  • 1
  • Possible duplicate of http://stackoverflow.com/questions/5178697/mysql-insert-into-multiple-tables-database-normalization – SameOldNick Apr 30 '16 at 22:40
  • 1
    Your question says *"I want to **insert** data ... at a later time"* but your logic expressed as (invalid) SQL query suggests you want to **update** an existing row (at a later time). Which one is the correct logic you want to implement? – axiac Apr 30 '16 at 22:46

1 Answers1

0

It sounds like you really want to update the second table, not insert into it. INSERT is for creating new rows, UPDATE is for modifying existing rows.

You do this by using a JOIN in an UPDATE statement.

UPDATE Table2 AS t2
JOIN Table1 AS t1 ON t1.id = t2.id
SET t2.col1 = t1.x1, t2.col2 = t1.x2, t2.col3 = t1.x3
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • Thanks @Barmar. Solved my problem. – Charles Jun 03 '16 at 14:27
  • Mind answering my curiosity: How does someone learn SQL and not learn the difference between INSERT and UPDATE? It seems like it should be one of the first things explained in any tutorial. – Barmar Jun 03 '16 at 14:32
  • I guess where I needed it for a quick task, I overlooked the simple things of SQL. – Charles Jul 23 '16 at 22:27