阿木伯 著 |
|
如何查詢出primary key和forgen key的關(guān)系表? |
|
- 說明:
SQL> create user a identified by a; --創(chuàng)建測試用戶a
SQL> grant connect,resource to a; --給用戶a授權(quán)
SQL> conn a/a --以用戶a連接
SQL> create table a1(a11 number primary key);
SQL> insert into a1 values(1);
SQL> insert into a1 values(2);
SQL> insert into a1 values(3);
SQL> commit;
SQL> create table b1
2 (
3 b11 char(1),
4 b12 number,
5 foreign key(b12) references a1(a11)
6 )
7 /
SQL> insert into b1 values('a',4);
insert into b1 values('a',4)
*
ERROR 位于第 1 行:
ORA-02291: 違反完整約束條件 (A.SYS_C001241) - 未找到父項(xiàng)關(guān)鍵字
注:a1表中a11列上只有1、2、3這三個(gè)值,而b1表中的列b12定義時(shí)引用了a1表中的a11列,
那么,在向b1表中錄入記錄時(shí),b12列只能錄1、2、3,而不能輸入4。
SQL> create table a2(a21 number primary key);
SQL> insert into a2 values(1);
SQL> insert into a2 values(2);
SQL> insert into a2 values(3);
SQL> commit;
SQL> create table b2
2 (
3 b21 char(1),
4 b22 number,
5 foreign key(b22) references a2(a21)
6 )
7 /
注:以下語句查詢primary key和forgen key的關(guān)系表
SQL> col 外鍵擁有者 format a10
SQL> col 外鍵表 format a10
SQL> col 主鍵擁有者 format a10
SQL> col 主鍵表 format a10
SQL> col 外鍵列 format a15
SQL> col 主鍵列 format a15
select
a.owner 外鍵擁有者,
a.table_name 外鍵表,
c.column_name 外鍵列,
b.owner 主鍵擁有者,
b.table_name 主鍵表,
d.column_name 主鍵列
from
user_constraints a,
user_constraints b,
user_cons_columns c,
user_cons_columns d
where
a.r_constraint_name=b.constraint_name
and a.constraint_type='R'
and b.constraint_type='P'
and a.r_owner=b.owner
and a.constraint_name=c.constraint_name
and b.constraint_name=d.constraint_name
and a.owner=c.owner
and a.table_name=c.table_name
and b.owner=d.owner
and b.table_name=d.table_name
/
外鍵擁有者 外鍵表 外鍵列 主鍵擁有者 主鍵表 主鍵列
---------- ---------- --------------- ---------- ---------- ------
A B1 B12 A A1 A11
A B2 B22 A A2 A21
|
【最后更新:】 |
|