简体   繁体   English

MySQL:在通过外键链接的表中插入记录

[英]MySQL: inserting records in tables linked by foreign key

In MySQL, is it possible to have two tables linked by a foreign key and when a record is inserted into the parent table to create a corresponding record in the child table? 在MySQL中,是否有可能有两个通过外键链接的表,以及何时在父表中插入记录以在子表中创建对应的记录?

I have a website that handles member registrations. 我有一个处理会员注册的网站。 One table contains the member's details such as name and email address, and is linked to a settings table via member ID. 一个表包含成员的详细信息,例如姓名和电子邮件地址,并通过成员ID链接到设置表。 What I would like is for a corresponding record to be entered into the settings table automatically when I create a new member. 我想要的是在创建新成员时将相应记录自动输入到设置表中。 Is this possible? 这可能吗? Or will that involve a stored procedure? 还是会涉及到存储过程?

I think what you might need is a trigger. 我认为您可能需要一个触发器。

http://dev.mysql.com/doc/refman/5.0/en/triggers.html http://dev.mysql.com/doc/refman/5.0/en/triggers.html

CREATE TRIGGER ins_settings AFTER INSERT ON members
  FOR EACH ROW BEGIN
    INSERT INTO settings SET member_id = NEW.member_id
    ...
  END;

Thanks to Greg, I managed to arrive at the solution, which is: 感谢Greg,我设法找到了解决方案,它是:

CREATE TRIGGER ins_settings AFTER INSERT ON members
FOR EACH ROW
INSERT INTO settings SET member_id = NEW.member_id;

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

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