MySQL-如何使用外键插入多个表 [英] MySQL - How to insert into multiple tables with foreign keys

查看:112
本文介绍了MySQL-如何使用外键插入多个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是MySQL的新手,所以请保持亲切:)

I'am new to MySQL, so please be nice :)

我想将来自php表单的数据插入3个不同的表中,这些表都具有外键.如何编写一次可同时更新所有3个表的插入命令,因为如果尝试手动更新表,则会由于缺少引用而收到错误消息. 我是否必须处理"NULL"条目并更新另一个表,还是可以用一个命令解决这个问题?像MySQLi_Multi_Query吗?

I would like to insert data from a php form into 3 different tables, which all have foreign keys. How can I write an insert command which updates all 3 tables at once, because if I try to update a table manually then I get an error because of the missing references. Do I have to deal with "NULL" entries and update every table after another or is it possible to solve this with one single command? Like MySQLi_Multi_Query?

非常感谢!

推荐答案

您最有可能必须按照相关性顺序插入内容.因此,如果您有三个表(A,B和C),我们假设C依赖于B,B依赖于A.我们还假设每个表分别具有主键AID,BID和CID.

You're most likely going to have to insert things in order of their dependence. So if you have three tables (A, B, and C) we'll assume C depends on B and B depends on A. We'll also assume each table has primary keys AID, BID, and CID respectively.

  1. 您需要将行插入A并获得AID.
  2. 然后,您将使用从步骤1获得的AID将行插入到B中.
  3. 然后,您将使用从第2步(也许是1)中获得的BID(也许是AID)将行插入C中

这篇关于MySQL-如何使用外键插入多个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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