SQL - How to create a new relation between tables A & C based on an existing relationship between A & B - en mass?
I have the following tables in a MySQL 5.x database:
Users:
id
county_id
state_id
Counties:
id
state_id
States:
id
States is a new table, each County belongs to one State, each user up until now has belonged to a single County - I want to be able to directly associate a user with a State and then delete the Counties table.
I can find out which state a user bel开发者_开发技巧ongs to be referencing user-> county-> state & can re-associate individual users with something like the following pseudo-SQL:
UPDATE users
SET state_id = (SELECT id FROM state WHERE state_id=(SELECT state_id FROM counties WHERE id=users.county_id) )
WHERE user_id=324235;
but not sure how to do this for all 320k+ users in my database.
Any ideas?
Try this:
UPDATE FROM users AS u
INNER JOIN counties as c
ON u.county_id = c.id
INNER JOIN states as s
ON c.state_id = s.id
SET u.state_id = s.id
Then put on a pot of coffee. 320k records might take a bit. You can look at deleting your indexes before executing the update and then recreating them when you are done. This could save you the time of having to update indexes as well as the table.
精彩评论