Oracle获得外键

mae*_*sto 9 sql oracle foreign-keys

我想在模式中获取所有外键,就像这样.假设我有桌子

users(id, username, pass, address_id)

addresses(id, text)

我已经将users-address_id上的FK定义为地址中的id列.我应该如何编写一个返回FK列的查询,例如:users,address_id,addresses,id?

谢谢!

SELECT *
FROM all_cons_columns a
JOIN all_constraints c ON a.owner = c.owner
    AND a.constraint_name = c.constraint_name
JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
    AND c.r_constraint_name = c_pk.constraint_name
WHERE  C.R_OWNER = 'TRWBI'
Run Code Online (Sandbox Code Playgroud)

mae*_*sto 13

找到了!

这就是我所寻求的,感谢大家的帮助.

SELECT a.table_name, a.column_name, uc.table_name, uc.column_name 
                FROM all_cons_columns a
                JOIN all_constraints c ON a.owner = c.owner
                    AND a.constraint_name = c.constraint_name
                JOIN all_constraints c_pk ON c.r_owner = c_pk.owner
                       AND c.r_constraint_name = c_pk.constraint_name
                join USER_CONS_COLUMNS uc on uc.constraint_name = c.r_constraint_name
                WHERE  C.R_OWNER = 'myschema'
Run Code Online (Sandbox Code Playgroud)


Moh*_*ari 7

使用@maephisto解决方案会出现一个小错误:
如果source tables primary key is a composite key然后运行查询将导致duplicate unnecessary records.

考虑T1和T2表:
主表T1:

create table T1
(
  pk1 NUMBER not null,
  pk2 NUMBER not null
);
alter table T1
  add constraint T1PK primary key (PK1, PK2);
Run Code Online (Sandbox Code Playgroud)

细节表T2:

create table T2
(
  pk1   NUMBER,
  pk2   NUMBER,
  name1 VARCHAR2(100)
);
alter table T2
  add constraint T2FK foreign key (PK1, PK2)
  references T1 (PK1, PK2);
Run Code Online (Sandbox Code Playgroud)

@maephisto查询的结果将是:

在此输入图像描述

为了解决问题,下面的查询将用于:

SELECT master_table.TABLE_NAME  MASTER_TABLE_NAME,
       master_table.column_name MASTER_KEY_COLUMN,
       detail_table.TABLE_NAME  DETAIL_TABLE_NAME,
       detail_table.column_name DETAIL_COLUMN
  FROM user_constraints  constraint_info,
       user_cons_columns detail_table,
       user_cons_columns master_table
 WHERE constraint_info.constraint_name = detail_table.constraint_name
   AND constraint_info.r_constraint_name = master_table.constraint_name
   AND detail_table.POSITION = master_table.POSITION
   AND constraint_info.constraint_type = 'R'
   AND constraint_info.OWNER = 'MY_SCHEMA'
Run Code Online (Sandbox Code Playgroud)


在此输入图像描述