简体   繁体   English

我应该如何用外键在mysql数据库中导入单独的表?

[英]How should I import separate table in mysql database with foreign key?

I use Mysql and PHP and My database have constraint. 我使用Mysql和PHP,并且我的数据库有约束。 I have made a function to import an sql file for a whole database by these step: 我通过以下步骤实现了为整个数据库导入sql文件的功能:

  1. Begin transaction. 开始交易。
  2. Read the file by using fopen. 通过使用fopen读取文件。
  3. Match and remove all comment in file while I collect a whole query by using delimiter ";" 当我使用定界符“;”收集整个查询时,匹配并删除文件中的所有注释 to an array. 到一个数组。
  4. Set check foreign key to 0 将检查外键设置为0
  5. Drop or truncate all tables. 删除或截断所有表。
  6. Run query one by one query element of array. 数组的查询元素逐一运行查询。
  7. Set check foreign key to 1 将检查外键设置为1
  8. Commit transaction 提交交易
  9. In case any thing else is fail (try catch), rollback transaction is trigger. 万一其他事情失败(尝试捕获),则触发回滚事务。

Everything is work fine. 一切正常。 However, now I have to expand it. 但是,现在我必须扩展它。 I have to make an import system which can import for individual functionality of website. 我必须制作一个可以针对网站的单个功能进行导入的导入系统。 It means I have to make an system can import individual tables and keep the constraint of them. 这意味着我必须使系统可以导入单个表并保持它们的约束。 For example, my system have tables user, article... when import article (export from local and import to development server) I have to check the user_id to make sure the application have this user (on development). 例如,当导入文章(从本地导出并导入到开发服务器)时,我的系统具有表user,article ...,我必须检查user_id以确保应用程序具有该用户(开发中)。 I've never done anything like this before. 我以前从未做过这样的事情。 I look like very complicated. 我看起来很复杂。

Therefore, I want to ask anyone how to do it? 因此,我想问任何人怎么做? How many way to do it? 有多少种方法? and Which is the best solution to do it? 哪个是最好的解决方案? Or If you have many experience, Could you please share to me where should I find to learn it or which book I should read to improve practice in database solution? 或者,如果您有丰富的经验,能否请您分享给我,我应该在哪里找到该书,或者应该阅读哪本书来改善数据库解决方案的实践?

You can switch off foreign keys constraints: 您可以关闭外键约束:

-- switch off
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

-- make import

-- switch on
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;

You can load your import data into a temporary table and look for invalid rows in it. 您可以将导入数据加载到临时表中,并在其中查找无效的行。

DROP TEMPORARY TABLE IF EXISTS tmp_import_article;
CREATE TEMPORARY TABLE tmp_import_article LIKE article;

-- TODO: load or insert import data into tmp_import_article

-- select invalid rows
SELECT tia.*
FROM tmp_import_article tia
LEFT JOIN `user` u ON u.user_id = tia.user_id
WHERE u.user_id IS NULL;

If you get an empty result, then everything is fine and you can insert the data from temporary table into the real one. 如果结果为空,则一切正常,您可以将临时表中的数据插入到真实表中。

If you get a not empty result - show it to the user in an error message. 如果得到的结果不是空的,请在错误消息中向用户显示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM