views:

52

answers:

3

Scenario: I have users that want to be able to change their username (unfortunately I didn't think about adding this functionality when I started the site), but the MySQL database has 110 tables.

Am I going to have to just make a script that executes 110 queries to update the username in each table (and remember to update the script when I add new tables), or is there a way to link the fields in all of the tables, so updating the username in one table updates it in all of the others?

A: 

You can use foreign key constraints with ON UPDATE CASCADE to automatically update foreign keys when they are modified (InnoDB only).

But it would be better not to use the username as a foreign key. You should normally use a surrogate key as a foreign key so that this is not an issue.

Mark Byers
This is for InnoDB tables only, it has not been implemented in MyISAM
danielrsmith
Indeed, thanks for pointing it out. I added it to my answer.
Mark Byers
+1  A: 

I'm assuming you're using the username as your primary key, since you've seen the need to do this. Change your table structure to use an auto_increment ID as the primary key instead of usernames, and refer to the ID from the other tables, rather than the name directly. This prevents duplication of the username across tables and lets you change a username by only updating a single table.

Note that you may want to keep a UNIQUE index on the username itself to prevent duplicates: currently, you get that for "free" by using the name as the PK, and you can continue to let the DB manage it by making a new index.

Michael Madsen
In a reply to my comment he said he he has an autoincrement id for every user, and I think that it is also his primary key.
Mark Byers
+1  A: 

You can setup the tables to do CASCADING updates.

This is accomplished by using foreign keys and the ON UPDATE CASCADE

Here is a good article on it: http://www.oreillynet.com/onlamp/blog/2004/10/hey_sql_fans_check_out_foreign.html

And the official MySQL page: http://dev.mysql.com/doc/refman/5.1/en/ansi-diff-foreign-keys.html

UNFORTUNATELY this is for InnoDB only, so you would have to switch the tables over.

danielrsmith