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.
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.
发布评论
评论(3)
您可以设置表来执行级联更新。
这是通过使用外键和
ON UPDATE CASCADE
来完成的,这是一篇关于它的好文章:http://www.oreillynet.com/onlamp/blog/2004/10/hey_sql_fans_check_out_foreign.html
以及官方 MySQL 页面:
http://dev.mysql.com/ doc/refman/5.1/en/ansi-diff-foreign-keys.html
不幸的是,这仅适用于 InnoDB,因此您必须切换表。
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.
我假设您使用用户名作为主键,因为您已经看到了这样做的必要性。更改表结构以使用 auto_increment ID 作为主键而不是用户名,并引用其他表中的 ID,而不是直接引用名称。这可以防止跨表的用户名重复,并允许您仅通过更新单个表来更改用户名。
请注意,您可能希望在用户名本身上保留一个唯一索引以防止重复:目前,您可以通过使用名称作为 PK 来“免费”获得该索引,并且您可以继续让数据库通过创建新索引来管理它。
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.
您可以使用外键约束 ON UPDATE CASCADE 在外键被修改时自动更新(仅限 InnoDB)。
但最好不要使用用户名作为外键。您通常应该使用代理键作为外键,这样就不会出现问题。
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.