是否可以用 mysqldump 命令导出一个文件,有两个表,其中一个有外键?

Is it possible to export one file with mysqldump command, with two tables , which one of them has foreign key?

我想知道是否可以导出一个文件包含两个表和FK?我发现你可以把 fk 放在 1 上......但是我可以设置 --where with table1.id = table2.id_tab1 ?

mysqldump -u root -p DBNAME SET FOREIGN_KEY_CHECKS = 1 --where table1.id = table2.id_tab1 ;

不,你不能那样做。

Mysqldump 基本上是这样做的:

for each table {
    SELECT * FROM $table WHERE $where;
}

它一次只读取 table 一个,不进行连接。所以你在参数中给出的 WHERE 子句不可能引用多个 table。这也意味着您提供的 WHERE 子句必须适用于 every table dumped.

我能够使用子查询来欺骗它,但这仅限于一次转储一个 table。

我创建了 tables:

create table test.parent (id int auto_increment primary key);
create table test.child (parent_id int, foreign key (parent_id) references test.parent(id));

将行放入父级,将一行放入子级:

INSERT INTO parent (id) VALUES (1),(2),(3);
INSERT INTO child (parent_id) VALUES (1);

现在尝试转储 parent:

mysqldump test parent
...
INSERT INTO `parent` VALUES (1),(2),(3);

这可以从一个 table.

中转储所有行

我们不能进行连接,但是我们可以在 WHERE 子句中使用一些东西来让它检查 child table,所以我们只得到与 [= 中的行匹配的行18=]?

mysqldump test parent --where="exists(select * from child where parent_id=parent.id)"
...
mysqldump: Couldn't execute 'SELECT /*!40001 SQL_NO_CACHE */ * FROM `parent`
WHERE exists(select * from child where parent_id=parent.id)': 
Table 'child' was not locked with LOCK TABLES (1100)

哎呀?我们可以让它不需要锁吗?

mysqldump --help
...
  -l, --lock-tables   Lock all tables for read.
                      (Defaults to on; use --skip-lock-tables to disable.)

是的!

mysqldump --skip-lock-tables test parent --where="exists(select * from child where parent_id=parent.id)"
...
INSERT INTO `parent` VALUES (1);

所以现在它转储来自 parent 的数据,但将行限制为在 child.

中具有匹配行的行