当一个数据库中存在大量外键约束时,您可能发现难以可视化表之间的外键关系。本文将探讨如何编写 SQL 查询来查找 DB2 for Linux, UNIX, and Windows 中的外键关系。
文中将讨论以下变体。
给定一个外键父表,返回 RI(参照
完整性)子表和后代表,以及从附表到这些子表和后代表的 RI 关系路径。 修改所提供的查询,以返回数据库中所有表的结果。
样例模式
清单 1 中所示的样例模式将用于本文中的示例。
清单 1. 样例模式
set schema newton; create table grandparent (i1 int not ">null primary key, i2 int, i3 int);create table parent (i1 int not null primary key, i2 int);create table parent2 (i1 int not null primary key, i2 int);create table child (i1 int not null primary key, i2 int, i3 int);create table grandchild (i1 int not null primary key, i2 int, i3 int); alter table parent add constraint fkp1 foreign key (i2) references grandparent;alter table parent2 add constraint fkp2 foreign key (i2) references grandparent;alter table child add constraint fk1 foreign key (i2) references parent;alter table child add constraint fk2 foreign key (i3) references parent2;alter table grandchild add constraint fk3 foreign key (i2) references child;alter table grandchild add constraint fk4 foreign key (i3) references parent2; create table gp (i1 int not null, i2 int not null, i3 int, primary key (i1, i2));create table p1 (i1 int not null primary key, i2 int, i3 int);create table c11 (i1 int not null primary key, i2 int);create table c12 (i1 int not null primary key, i2 int); alter table p1 add constraint fkp1 foreign key (i2, i3) references gp;alter table c11 add constraint fkc11 foreign key (i2) references p1;alter table c12 add constraint fkc12 foreign key (i2) references p1;alter table gp add constraint fkgp1 foreign key (i2) references c12; create table self (i1 int not null primary key, i2 int);alter table self add constraint fk_self foreign key (i2) references self;