我有两个表,UserData 和 Response
UserData 有字段 --
ID smallint unsigned not null auto_increment,
Name varchar(50)
Age tinyint unsigned
PRIMARY KEY(ID)
响应有字段 --
ResponseID smallint auto_increment,
field1 text,
field2 text,
yesno bit default 0,
User_ID smallint not null unique
PRIMARY KEY(ID)
FOREIGN KEY(User_ID) references UserData(ID)
我有一个表单,用户可以在其中输入详细信息 姓名、年龄、字段 1、字段 2 和是否
现在来自用户计算机的数据将全部汇集在一起,但它将被插入到数据库中,以便前两个字段将进入 UserData 表,其余字段将进入 Response。
在我的应用程序逻辑中,我想做这样的事情 -
插入该用户的用户数据(姓名,年龄) 获取 UserData 中新插入的行的 ID 列值作为 UID 为该用户插入 Response(field1,field2,yesno),其中 User_ID = UID
假设如果 UserData 中的 ID 为 100,则相应行的 Response 中的 User_ID 将为 100。
这样稍后我就可以通过 WHERE User_ID = UserData.ID
查询检索该用户的响应
我该怎么做? last_insert_id() 是这样吗?
最佳答案
如果您在 MySQL 端处理插入,那么可以使用 LAST_INSERT_ID()
。
如果您从客户端代码(例如 php )执行此操作,则使用其对应项,如 mysql_insert_id()
在 mysql_*
或 lastInsertId()
中在PDO
INSERT INTO UserData (Name, Age) VALUES ('Jhon Doe', 35);
INSERT INTO Response (field1, field2, yesno, User_ID)
VALUES ('some text', 'more text', 0, LAST_INSERT_ID());
这里是SQLFiddle 演示
更新关于评论中您的疑虑
The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.
关于mysql - 从 mysql 中新创建的外键值创建记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18823309/