简体   繁体   中英

Alter sql table with new foreign key values

I have 'locations' database and two tables. My first table was 'uszips' which looks like:

--id--zipCode--stateCode--latitude--longitude--
   1    35004         AL  33.584132 -86.515570
   2    35005         AL  33.588437 -86.959727

Now, I have a second table called 'usstates' and I have 2-letter state codes already there:

--id--stateCode--
   1         AK
   2         AL

I was not able to write a query to modify 'uszips' table as 'stateCode' column would be 'stateId' to be foreign keys of the 'usstates'. For example:

--id--zipCode--stateId--latitude--longitude--
   1    35004        2  33.584132 -86.515570
   2    35005        2  33.588437 -86.959727

My best try is:

update uszips set uszips.stateCode=usstates.id
from uszips
join usstates on (uszips.stateCode=usstates.state)

But I recieve the following error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from uszips join usstates on (uszips.stateCode=usstates.state)' at line 2

The set clause should come after the join clause:

UPDATE uszips
JOIN   usstates ON uszips.stateCode = usstates.state
SET    uszips.stateCode = usstates.id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM