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