简体   繁体   中英

create a record from a newly created foreign key value in mysql

I have two tables, UserData and Response

UserData has fields --

ID smallint unsigned not null auto_increment, 
Name varchar(50)
Age tinyint unsigned
PRIMARY KEY(ID)

Response has fields --

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)

And I have a form in which the user inputs details for Name, Age, field1, field2 annd yesno

Now the data from the user's computer will all come together, but it will be inserted into the database such that first two fields will go into UserData table, and the rest into Response.

In my application logic I want to do something like this -

insert UserData(name,age) for the THIS user get ID column value as UID, of that freshly inserted row in UserData insert Response(field1,field2,yesno) for the THIS user, where User_ID = UID

Say if the ID in UserData is 100, then User_ID will be 100 in Response for the corresponding row. So that later on I can retrieve that user's response by a WHERE User_ID = UserData.ID query

How do I do that? last_insert_id() does that?

If you handle your inserts on MySQL side then yes use LAST_INSERT_ID() .

If you do it from your client code (egphp ) then use its counterpart like mysql_insert_id() in mysql_* or lastInsertId() in 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());

Here is SQLFiddle demo

UPDATE Regarding your concerns in comments

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM