简体   繁体   English

MySQL 自动分配外键ID

[英]MySQL auto assign foreign key ID

I have a main table called results .我有一个名为results的主表。 Eg例如

CREATE TABLE results (
    r_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    r_date DATE NOT NULL,
    system_id INT NOT NULL,
    FOREIGN KEY (system_id) REFERENCES systems(s_id) ON UPDATE CASCADE ON DELETE CASCADE
);

The systems table as:系统表如下:

 CREATE TABLE systems (
    s_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    system_name VARCHAR(50) NOT NULL UNIQUE
);

I'm writing a program in Python with MySQL connector.我正在使用 MySQL 连接器在 Python 中编写程序。 Is there a way to add data to the systems table and then auto assign the generated s_id to the results table?有没有办法将数据添加到systems表,然后自动将生成的s_id分配给results表?

I know I could INSERT into systems , then do another call to that table to see what the ID is for the s_name , to add to the results table but I thought there might be quirk in SQL that I'm not aware of to make life easier with less calls to the DB?我知道我可以INSERT into systems ,然后再次调用该表以查看s_name的 ID 是什么,以添加到results表中,但我认为 SQL 中可能存在我不知道的怪癖更少调用数据库更容易?

You could do what you describe in a trigger like this:您可以执行您在触发器中描述的操作,如下所示:

CREATE TRIGGER t AFTER INSERT ON systems
FOR EACH ROW
  INSERT INTO results SET r_date = NOW(), system_id = NEW.s_id;

This is possible only because the columns of your results table are easy to fill in from the data the trigger has access to.这是可能的,因为您的results表的列很容易从触发器有权访问的数据中填充。 The auto-increment fills itself in, and no additional columns need to be filled in. If you had more columns in the results table, this would be harder.自动增量会自行填充,不需要填充额外的列。如果results表中有更多列,这会更难。

You should read more about triggers:您应该阅读有关触发器的更多信息:

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

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