我想在模式中获取所有外键,就像这样。 假设我有桌子
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'
答案 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查询的结果将是:
为了解决问题,下面的查询将发挥作用:
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'
答案 2 :(得分:2)
它们列在系统视图ALL_CONSTRAINTS
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1037.htm#i1576022
修改强>
约束中涉及的列列在ALL_CONS_COLUMNS
http://download.oracle.com/docs/cd/B19306_01/server.102/b14237/statviews_1035.htm#i1575870