多对多关系INSERT [英] Many-to-many relationship INSERT

查看:228
本文介绍了多对多关系INSERT的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在2个表之间创建多对多关系。我有3个表。它遵循TOXY模型。

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?

这样吗? INSERT INTO('name')VALUES('my name');

INSERT INTO b('name')VALUES('my name');

将a.id和b.id放在表ab中。我应该如何检索它们?

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

我知道我可以做一个SELECT a.id FROM WHERE name ='my name'。但是没有一个更简单的方法,当u插入行时,自动返回一个id?

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?

推荐答案

所有你需要做的是将这些ID存储在变量中以在查询中使用,以插入到 ab 表中。 LAST_INSERT_ID()返回插入行的ID。所以,在PHP中例如:

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);");

这篇关于多对多关系INSERT的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆