小编典典

如何查找两个表之间的特定链接

sql

我有很多桌子,它们之间有很多关系。当我尝试在它们之间进行某种连接时,我总是在寻找两个表之间的关系。

为了简单起见,让我们说,我有 表AB表 。它们与外键链接。

问:如何在这两个确切的表及其引用的列之间找到外键?并不是所有引用此表的表或外键。


阅读 157

收藏
2021-05-16

共1个答案

小编典典

您可以将与数据字典约束相关的视图彼此连接在一起,并相互查找任何引用约束的两端。

有点粗糙,但类似:

select uc1.constraint_name, uc1.table_name, ucc1.column_name,
  uc2.constraint_name, uc2.table_name, ucc2.column_name
from user_constraints uc1
join user_cons_columns ucc1 on ucc1.constraint_name = uc1.constraint_name
join user_constraints uc2 on uc2.constraint_name = uc1.r_constraint_name
join user_cons_columns ucc2 on ucc2.constraint_name = uc2.constraint_name
and ucc2.position = ucc1.position
where uc1.table_name in (<table1>, <table2>)
and uc1.constraint_type = 'R'
and uc2.table_name in (<table1>, <table2>)
and uc2.constraint_type in ('P', 'U');

我假设您可能具有复合键,并且不知道这两个表之间的关系是哪种方式-
因此在here子句的两个过滤器中查找任一名称。我还通过使用user_tables甚至忽略了该owner列来简化了一点-
如果引用跨越了模式,则可以包括该模式,并使用all_*表而不是这些表user_*

快速演示:

create table t1 (
  id number,
  uniq1 number,
  uniq2 number,
  constraint t1_pk primary key (id),
  constraint t1_uk unique (uniq1, uniq2)
);

create table t2 (
  id number,
  t1_id number,
  t1_uniq1 number,
  t1_uniq2 number,
  constraint t2_fk_1 foreign key (t1_id) references t1 (id),
  constraint t2_fk_2 foreign key (t1_uniq1, t1_uniq2) references t1 (uniq1, uniq2)
);

select uc1.constraint_name as foreign_key,
  uc1.table_name as child_table,
  ucc1.column_name as child_column,
  ucc1.position,
  uc2.constraint_name as pri_or_uniq_key,
  uc2.table_name as parent_table,
  ucc2.column_name as parent_column
from user_constraints uc1
join user_cons_columns ucc1 on ucc1.constraint_name = uc1.constraint_name
join user_constraints uc2 on uc2.constraint_name = uc1.r_constraint_name
join user_cons_columns ucc2 on ucc2.constraint_name = uc2.constraint_name
and ucc2.position = ucc1.position
where uc1.table_name in ('T1', 'T2')
and uc1.constraint_type = 'R'
and uc2.table_name in ('T1', 'T2')
and uc2.constraint_type in ('P', 'U')
order by foreign_key, position;



FOREIGN_KEY   CHILD_TABLE   CHILD_COLUMN   POSITION   PRI_OR_UNIQ_KEY   PARENT_TABLE   PARENT_COLUMN   
-----------   -----------   ------------   --------   ---------------   ------------   -------------
T2_FK_1       T2            T1_ID                   1 T1_PK             T1             ID              
T2_FK_2       T2            T1_UNIQ1                1 T1_UK             T1             UNIQ1           
T2_FK_2       T2            T1_UNIQ2                2 T1_UK             T1             UNIQ2
2021-05-16