簡體   English   中英

創建觸發器以在創建新行時將主鍵從一個表插入到 MySQL 中另一個表的列中

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

我正在使用兩張表:記錄和發票。 Invoice 包含一個列,用於將 Records 的主鍵存儲為外鍵。

我正在尋找創建觸發器。 立即在 Records 中生成新行時,我希望在 Invoice 中也創建一個新行,並且我希望將 Records 中的 PK 插入到 invoice 的相應列中。

例如,假設表是 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

我知道這很可能很遙遠,但這是我一直在研究的觸發器:

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 ;

任何幫助將不勝感激。 謝謝你。

是的,你幾乎是對的

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
  | 記錄ID |  |  --------: |  |  1 |

db<> 在這里擺弄

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM