Oracle获得外键

时间:2011-04-04 08:09:54

标签: 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'

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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);

详情表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);

@maephisto查询的结果将是:

enter image description here

为了解决问题,下面的查询将发挥作用:

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'


enter image description here

答案 2 :(得分:2)