简体   繁体   中英

Many-to-many relationship INSERT

I am trying to create a many to many relationship between 2 tables. I've got 3 tables for that. It follows TOXY model.

table a: a.id (primary key)
table ab: ab.a_id (foreign key) ab.b_id (foreign key)
table b: b.id (primary key)

How should I insert the data so it will be all linked up?

Like this? "INSERT INTO a ('name') VALUES ('my name')";

then like this? "INSERT INTO b ('name') VALUES ('my name')";

but then I have to have the a.id and b.id to put it in table ab. How should I retrieve them?

i know i could do a SELECT a.id FROM a WHERE name = 'my name'. but isnt there an easier way for this that automatically returns an id when u INSERT the row?

All you need to do is store those IDs in variables to use in a query to insert into the ab table. LAST_INSERT_ID() returns the ID of the inserted rows. So, in PHP for instance:

// Run command to insert into A, then:
$a = mysql_query('SELECT LAST_INSERT_ID();');

// Run command to insert into B, then:
$b = mysql_query('SELECT LAST_INSERT_ID();');

// Then $a and $b hold the IDs that you can use to insert into AB.
mysql_query("INSERT INTO ab (a_id, b_id) VALUES ($a, $b);");

您可以通过调用mysql_insert_id()函数来获取存储在auto_increment主键列中的

SELECT LAST_INSERT_ID()

I'm not sure what the TOXY model is, but you would use a simple join:

SELECT * FROM a INNER JOIN ab on a.id=ab.a_id WHERE ab.b_id = {b.id};

and for your instance, {b.id} would be last_insert_id();

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