0

I have a table like this:

table1
id   | name  | location
------------------------
1    | brian | null
2    | john  | null

and another table like this:

table2
id   | location
------------------------
2    |  USA
1    |  China

I want to INSERT the locations into the table1 ON t1.id=t2.id so table1 looks like this:

table1
id   | name  | location
------------------------
1    | brian | China
2    | john  | USA

For some reason though, when I run

INSERT INTO table1
SELECT location FROM table2
WHERE table1.id = table2.id;

I get a syntax error. Does anyone know how to insert it correctly?

bguan2020
  • 93
  • 1
  • 8
  • 1
    Don't under any circumstances share that error message with us. – Strawberry Jul 15 '20 at 21:01
  • Insert would create a new record. What you are looking for is update. But I'm curious why you would want to denormalise your data by moving location into the first table – Shadow Jul 15 '20 at 21:01
  • Your `location` field in `table1` has no purpose in 3rd Normal Form. Get rid of it, then: `SELECT t1.name, t2.location FROM table1 t1 JOIN table2 t2 ON t1.id = t2.id` – StackSlave Jul 15 '20 at 21:51

1 Answers1

0

Actually you want to update Table1:

UPDATE table1 t1
INNER JOIN table2 t2
ON t1.id = t2.id
SET t1.location = t2.location;
forpas
  • 160,666
  • 10
  • 38
  • 76