简体   繁体   English

创建触发器以在创建新行时将主键从一个表插入到 MySQL 中另一个表的列中

[英]Create trigger to insert primary key from one table upon creation of new row, into column of another table in MySQL

I have two tables I'm working with: Records and Invoice.我正在使用两张表:记录和发票。 Invoice contains a column for the primary key of Records to be stored as a foreign key. Invoice 包含一个列,用于将 Records 的主键存储为外键。

I'm looking to create a trigger.我正在寻找创建触发器。 Immediately when a new row is generated in Records, I want a new row to also be created in Invoice, and I want the PK from Records to be inserted into the corresponding column in invoice.立即在 Records 中生成新行时,我希望在 Invoice 中也创建一个新行,并且我希望将 Records 中的 PK 插入到 invoice 的相应列中。

For example, let's say the tables are Records(RecordsID) and invoice(invoiceID, RecordsID)例如,假设表是 Records(RecordsID) 和 invoice(invoiceID, RecordsID)

When new row created in tbl Records     
Create new row in tbl Invoice and insert new Records.RecordID into new invoice.invoiceID

I'm aware this is most likely very far off, but here is the trigger I've been working on:我知道这很可能很遥远,但这是我一直在研究的触发器:

DELIMITER $$

create trigger new_invoice
after insert
on main for each row
begin
if new.RecordID is not null then
insert into invoice(RecordID)
values(new.RecordID(new.RecordID));
END IF;

END$$
DELIMITER ;

Any assistance will be greatly appreciated.任何帮助将不胜感激。 Thank you.谢谢你。

Yes you have it almost right是的,你几乎是对的

CREATE tABLE main(RecordID int)
 CREATE tABLE invoice (RecordID int)
 create trigger new_invoice after insert on main for each row begin if new.RecordID is not null then insert into invoice(RecordID) values(new.RecordID); END IF; END
 INSERT INTO main VALUES (1)
 SELECT * FROM invoice
 | | RecordID |记录ID | | | -------: | --------: | | | 1 | 1 |

db<>fiddle here db<> 在这里摆弄

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

相关问题 使用触发器将新行从另一表插入到一个表? - Use trigger to INSERT new row to one table from another table? MySQL:触发在另一个表中插入一行时在一个表中插入新行 - MySQL: Trigger to Insert New Row in One Table When Another Table has a Row Inserted 使用已存在的主键将新行插入mysql表 - Insert new row into mysql table with already-existing primary key Java/Mysql 从一个表中选择主键值并将它们作为外键插入到另一个表中 - Java/Mysql Selecting Primary Key values from one table and Insert them to another table as Foreign Keys Mysql-创建触发器以根据另一张表中插入的行插入新行 - Mysql - Create trigger to insert a new row based on a row inserted in another table 创建触发器以在MySQL的另一个表中插入新行时更新表 - create trigger to update a table on inserting new row in another table in MySQL 如何将一个表的主键值插入另一个表的外键列? - How do I insert primary key value from one table to foreign key column in another? MySQL触发器在更新后将新行插入另一个表 - Mysql trigger to insert a new row into another table after an update MySQL - 将主键从一个表插入另一个表(外键) - MySQL - Inserting Primary Key from one table to another (Foreign Key) 将主键连接到MySQL中另一个表的行 - Connecting a primary key to row of another table in MySQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM