简体   繁体   中英

How to create insert scripts for tables with FK relationships

create table foo(id, val1)
create table foo_bars(id, foo_id, val2)

id is auto generated in the above case.

I want to do the following

insert into foo (val1) values (1)
insert into foo_bars (foo_id, val2) values (?, 2)

How do I fetch the value of foo_id if its not known to me. Do I need to hard-code these id(s) also. Is there an elegant way?

Yes there is an elegant way of determing the last inserted id.

check this for MySQL and this for MySQLi

From their examples:

$query = "INSERT INTO myCity VALUES (NULL, 'Stuttgart', 'DEU', 'Stuttgart', 617000)";
$mysqli->query($query);

printf ("New Record has id %d.\n", $mysqli->insert_id);

According to the mysql site ( http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html )

Try this (if you want to use pure MySQL):

INSERT INTO foo (val1) 
    VALUES(1);         
INSERT INTO foo_bars (foo_id, val2)
    VALUES(LAST_INSERT_ID(),2);  # use ID in second table

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