Oracle SQL:外键目标表

时间:2017-08-03 09:52:40

标签: sql oracle key

我想写一个SQL来查看FK'S。到目前为止我得到了什么:

SELECT OWNER,
       CONSTRAINT_TYPE,
       TABLE_NAME,
       R_OWNER,
       R_CONSTRAINT_NAME
  FROM ALL_CONSTRAINTS
 WHERE     OWNER = 'XXX'
       AND TABLE_NAME = 'XXX'
       AND CONSTRAINT_TYPE = 'R'

问题:我没看到FK映射到的位置。您有R_OWNER和R_CONSTRAINT_NAME,但没有R_TABLE。无论如何,这可以通过编写SQL来完成吗?

2 个答案:

答案 0 :(得分:0)

更新。

这可以满足您的需求:

select
    cc.owner,
    cc.constraint_name, 
    cc.table_name, 
    cc.column_name, 
    c.r_owner,
    c_pk.table_name r_table_name, 
    c_pk.constraint_name r_pk
from all_cons_columns cc
join all_constraints c on cc.owner = c.owner and cc.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.constraint_type = 'R' 
and cc.owner = 'XXX'
and cc.table_name = 'XXX';

答案 1 :(得分:-1)

您可以获取所有现有外键的列表:

         SELECT RC.CONSTRAINT_NAME FK_Name,
               KF.TABLE_SCHEMA FK_Schema,
               KF.TABLE_NAME FK_Table,
               KF.COLUMN_NAME FK_Column,
               RC.UNIQUE_CONSTRAINT_NAME PK_Name,
               KP.TABLE_SCHEMA PK_Schema,
               KP.TABLE_NAME PK_Table,
               KP.COLUMN_NAME PK_Column,
               RC.MATCH_OPTION MatchOption,
               RC.UPDATE_RULE UpdateRule,
               RC.DELETE_RULE DeleteRule
         FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS RC
             JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KF ON RC.CONSTRAINT_NAME = KF.CONSTRAINT_NAME
             JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE KP ON RC.UNIQUE_CONSTRAINT_NAME = KP.CONSTRAINT_NAME;