Oracle get foreign keys

后端 未结 3 585
有刺的猬
有刺的猬 2020-12-06 17:35

I\'d like to get all foreign keys in a schema, like this. Let\'s say I have tables

users(id, username, pass, address_id)

and

addr

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-06 18:23

    Using @maephisto solution will case a little bug:
    If the source tables primary key is a composite key then running the query will result duplicate unnecessary records.

    Consider T1 and T2 tables:
    Master table T1:

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

    Detail table 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);
    

    The result of the @maephisto query will be:

    enter image description here

    To over come the problem the query bellow will serve:

    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

提交回复
热议问题