[英]Insert using LAST_INSERT_ID
How would I go about inserting while incrementing and using LAST_INSERT_ID? 在增加和使用LAST_INSERT_ID时如何插入? I have a table and trigger as such:
我有这样一个表和触发器:
CREATE TABLE A(
id int NOT NULL AUTO_INCREMENT,
name char(15),
PRIMARY KEY(id)
);
CREATE TABLE B(
id int NOT NULL,
name char(15),
FOREIGN KEY(id) REFERENCES A(id)
);
delimiter //
CREATE TRIGGER T
AFTER INSERT ON B
FOR EACH ROW
BEGIN
IF (NEW.name LIKE 'A') THEN
INSERT INTO A VALUES(LAST_INSERT_ID() + 1, 'A');
END IF;
END//
delimiter ;
I know that INSERT INTO B VALUES(LAST_INSERT_ID() + 1, 'A');
我知道
INSERT INTO B VALUES(LAST_INSERT_ID() + 1, 'A');
doesn't work if I have multiple inserts into B because LAST_INSERT_ID()
when doing multiple-row inserts, LAST_INSERT_ID()
will return the value of the first row inserted (not the last). 如果我有多个插入到B,因为不工作
LAST_INSERT_ID()
做多行插入,当LAST_INSERT_ID()
将返回插入的第一行(不是最后一个)的值。 How would I go about incrementing the ID so that LAST_INSERT_ID()
returns the most recent ID from the inserts` 我将如何增加ID以使
LAST_INSERT_ID()
返回插入中的最新ID?
If you want to insert the id from B
, then use the id column: 如果要从
B
插入id,请使用id列:
CREATE TRIGGER T
AFTER INSERT ON B
FOR EACH ROW
BEGIN
IF (NEW.name LIKE 'A') THEN
INSERT INTO A VALUES(B.ID + 1, 'A');
END IF;
END//
This seems like a curious expression. 这似乎是一种奇怪的表达。 Perhaps your real intention is simply to have an auto incremented id on both tables.
也许您真正的目的只是在两个表上都具有一个自动递增的id。
我意识到我可以插入A而无需id,因为它会自动增加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.