简体   繁体   English

MySQL 外键约束:更新一个表时,用第一个表中的一些数据填充另一个表

[英]MySQL foreign key constraints : on updating one table, fill another table with some data from the first table

I have two tables, users table and login table.我有两个表,用户表和登录表。 Say:说:

Create table users(
 id int not null,
 name varchar not null,
 email varchar not null,
 password varchar not null,
 entries int default 0,
 primary key(id));

Create table login(
 id int not null,
 email varchar not null,
 password varchar not null,
 user_id int not null,
 Primary key(id)),
 Foreign key (user_id) references users(id));

What constraints can I add or how can i work my way around such that whenever i add a user in the users table, the email and password columns are added into the login table too (just like to say i create a minimized version of the users table which only contains login credentials of users) .我可以添加哪些约束或如何解决问题,以便每当我在用户表中添加用户时, email密码列也会添加到登录表中(就像说我创建了用户的最小化版本仅包含用户登录凭据的表) And whenever i delete a user from the users table, he should be removed from the login table.每当我从用户表中删除一个用户时,他应该从登录表中删除。

I hope i have been descriptive enough我希望我已经足够描述了

You can define constraint with cascade delete .您可以使用 cascade delete 定义约束 To implement the update of dependent tables you need triggers .要实现依赖表的更新,您需要触发器 It is possible to define AFTER INSERT trigger where you can update any dependent tables.可以定义 AFTER INSERT 触发器,您可以在其中更新任何依赖表。

At the same time, I would reconsider having redundant fields in the dependent table when you always can obtain it by joining with the main table.同时,当您总是可以通过加入主表来获得它时,我会重新考虑在依赖表中使用冗余字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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