SQL> desc pp; --父表
Name Type Nullable Default Comments
---- ------- -------- ------- --------
A INTEGER Y
B INTEGER Y
SQL> desc child;--子表
Name Type Nullable Default Comments
---- ------- -------- ------- --------
C INTEGER Y
D INTEGER Y
SQL> alter table child add constraint fk_d foreign key (c) references pp(b);
alter table child add constraint fk_d foreign key (c) references pp(b)
ORA-02270: 此列列表的唯一或主键不匹配
以上说明要建立外键时(在子表上),主表上面(补子表所引用的)一定要构建主键或唯一索引
SQL> alter table pp add constraint pk_a primary key(a);
Table altered
SQL> alter table child add constraint fk_d foreign key (c) references pp(a);
Table altered
这篇博客讨论了在SQL中如何为表添加外键约束,强调了创建外键时主表需有主键或唯一索引的重要性。通过示例展示了在父表`pp`上添加主键以及在子表`child`上创建引用`pp`的外键的过程。
2127

被折叠的 条评论
为什么被折叠?



