简体   繁体   中英

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) . 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 . 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.

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.

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