[英]Many-to-many relationship INSERT
I am trying to create a many to many relationship between 2 tables. 我正在尝试在2个表之间创建多对多关系。 I've got 3 tables for that.
我有3张桌子。 It follows TOXY model.
它遵循TOXY模型。
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. 但是然后我必须将a.id和b.id放在表ab中。 How should I retrieve them?
我应该如何找回它们?
i know i could do a SELECT a.id FROM a WHERE name = 'my name'. 我知道我可以从WHERE name ='my name'进行SELECTa.id。 but isnt there an easier way for this that automatically returns an id when u INSERT the row?
但是有没有更简单的方法可以在u插入行时自动返回ID?
All you need to do is store those IDs in variables to use in a query to insert into the ab
table. 您需要做的就是将这些ID存储在变量中,以便在查询中使用以插入到
ab
表中。 LAST_INSERT_ID()
returns the ID of the inserted rows. LAST_INSERT_ID()
返回插入的行的ID。 So, in PHP for instance: 因此,例如在PHP中:
// 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: 我不确定TOXY模型是什么,但是您将使用简单的联接:
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(); 对于您的实例,{b.id}将为last_insert_id();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.