If two individual records are added to a database such as two patients being added to the table 'Paitents' and when they are added the Primary_Key such as Paitient_ID is created automatically and given to each new account. .(Auto Incremented) That bit is quite straight forward and understand I can just use an 'INSERT INTO SONGS' statement. But what if the two patients are related and I have another table called "Relations" Where by I need it to pull in the two Paitent_ID's and create a relation from the same insert query. Can this be done?
- Yes. You would need to insert into that table in the same way, as your database cannot automatically know when people are relatedAdrianBR– AdrianBR2015-09-18 12:50:11 +00:00Commented Sep 18, 2015 at 12:50
- How are you adding the patients? One-by-one in a form, POSTing the form for each patient? Or do you have a form on which more than one patient can be entered, and then the details of both posted together in one POST?foxbeefly– foxbeefly2015-09-18 12:51:19 +00:00Commented Sep 18, 2015 at 12:51
Add a comment |
1 Answer
ID generated by MySQL automatically in auto_increment column can be obtained using the LAST_INSERT_ID() function. Languages/libraries often offer a function for this (e.g. in PHP PDO you call PDO::lastInsertId() instead of making another query).
How to solve this exactly depends on how you are inserting the values into a database, but the basics can be:
- Insert patient one
- Get the ID
- Insert patient two
- Get the ID
- Create the relation
2 Comments
ROAL
Sure thing! You can simply use
SELECT LAST_INSERT_ID(). If you're working in MySQL only, I guess it would be best to use variables, like so: after first Patient insert, you SELECT LAST_INSERT_ID() INTO @patientOne, after second insert, you SELECT LAST_INSERT_ID() INTO @patientTwo, and then just INSERT INTO Relation VALUES @patientOne, @patientTwo.