【问题标题】:How to refer to a table, which is not yet created?如何引用尚未创建的表?
【发布时间】:2016-08-31 11:17:05
【问题描述】:

假设我需要创建两个相互引用的表(它们需要约束)。是创建没有约束的表的唯一方法,然后将它们添加到单独的语句中吗?我记得有些orms可以自己解决这个问题,但是是否可以只使用sql并在两个语句中做到这一点?

【问题讨论】:

  • 先创建两个表,然后修改它们以添加FK,如SQL Add foreign key to existing column
  • 这意味着不能使用schema dump来导入schema。
  • 在这种情况下,您可能无法使用模式转储。
  • 也许您可以将此视为摆脱此循环引用的机会。

标签: mysql sql


【解决方案1】:

您应该必须先创建不带外键的表,然后在创建两个表后附加它们:

create table t1 (id int not null primary key, id2 int not null);
create table t2 (id int not null primary key, id1 int not null);

alter table t1 add foreign key (id2) references t2(id);
alter table t2 add foreign key (id1) references t1(id);

好消息:架构转储完美运行(so 是我的数据库):

mysqldump -u root so t1 t2 | mysql -u root so

这不会出错,因为mysqldump 在正确的位置插入了DISABLE KEYS 和ENABLE KEYS。

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    相关资源
    最近更新 更多