繁体   English   中英

查询以获取父子表之间的约束

[英]query to get constraint between parent and child table

我是oracle新手,正在处理需要在2个表之间获取约束并将值作为另一个输入发送的表。

Table 1
  |_ Column1_pk
  |_ Column2 (foreign key to Table 2) 

Table 2
  |_column2 

所以我想获取具有两个表之间关系的table1和column的主键

您需要查询字典视图USER_CONSTRAINTSUSER_CONS_COLUMNS 例如:

DEPT有一个主键,表EMP有一个指向DEPT的外键。 首先,我们找到约束名称,然后找到DEPT主键的列。 然后,在拥有约束名称的情况下,我们找到约束名称,然后找到EMP外键的列。

select table_name, constraint_name, constraint_type
from   user_constraints
where  table_name      = 'DEPT'
  and  constraint_type = 'P'
;

TABLE_NAME  CONSTRAINT_NAME  CONSTRAINT_TYPE
----------  ---------------  ---------------
DEPT        PK_DEPT          P

select constraint_name, table_name, column_name, position
from   user_cons_columns
where  constraint_name = 'PK_DEPT'
;

CONSTRAINT_NAME  TABLE_NAME  COLUMN_NAME  POSITION
---------------  ----------  -----------  --------
PK_DEPT          DEPT        DEPTNO              1

接着

select table_name, constraint_name, constraint_type
from   user_constraints
where  table_name        = 'EMP'
  and  r_constraint_name = 'PK_DEPT'
;

TABLE_NAME  CONSTRAINT_NAME  CONSTRAINT_TYPE
----------  ---------------  ---------------
EMP         FK_DEPTNO        R

select constraint_name, table_name, column_name, position
from   user_cons_columns
where  constraint_name = 'FK_DEPTNO'
;

CONSTRAINT_NAME  TABLE_NAME  COLUMN_NAME  POSITION
---------------  ----------  -----------  --------
FK_DEPTNO        EMP         DEPTNO              1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM