Wednesday, November 13, 2013

[SQL] insert data into 2 table with related id

There is 2 table of this example : "tbl_share" & "tbl_share_photo"
And let have a view of the table first :
This is the table tbl_share :


And the table "tble_share_photo" :

--------------------------------------------------------------
What i should do is insert a record into table "tbl_share" first, and them

for my case, it's named  "share_id", is an auto_increase value and primary key in this value.
so i use this SQL script to get the latest record of "share_id"
SELECT MAX(share_id) FROM tbl_share;
and if my result is: 10
so 10 is a latest id of the record.

And since i need add a record to another table bu
Script 2:
SELECT MAX(share_id)+1 FROM tbl_share;
Result: 11

And i use the
embed Script 2 into script 1:

INSERT INTO tbl_share_photo (share_id, photo, position)
VALUES ((SELECT MAX(share_id)+1 FROM tbl_share),'fsdfsfsdf', '1');
And then would insert a row with same share_id (with tbl_share) into tbl_share_photo table.

tbl_share          :
tbl_share_photo:



No comments :

Post a Comment