2015-10-14 361 views
1

我正在使用数据库,并被告知表USERS有一个主键 - USERID。使用ALL_CONS_COLS给了我下面的:Oracle:查找主键 - PK和NN

OWNER | TABLE_NAME | CONSTRAINT_NAME | COLUMN_NAME | POSITION 
---------------------------------------------------------------- 
MONSTER | USERS | USER_ID_PK | USERREF | 2 
MONSTER | USERS | USER_ID_NN | USERID 
MONSTER | USERS | USER_ID_PK | USERID | 1 

这表明PK是由复合:USERREFUSERID

有几件事情我不明白:

为什么USERID既有NOT NULL约束,也是一个PK约束?根据定义,PK表示NN。 其次,由于USERIDNN约束,为什么USERREF没有NN约束? 第三,为什么CONSTRAINT_NAME“暗示”PKUSER_IDUSERID),即为什么是以单个列命名的约束; USERS_PK会不会是一个更好的约束名称?

因此,最终是不是合成PK

+0

俺们这些问题大部分都是(可能):因为有人用这种方式创建它(特别是名称和NN约束) –

+0

谢谢!那么它是一个复合'PK'? – monster

回答

2

那么,最终它是一个复合PK还是不是?

是。主键一起定义在两列上。该职位将告诉你领导专栏。 USER_ID_PK主键约束在USERID上定义为领先列,然后是USERREF

为什么USERID同时具有NOT NULL约束和PK约束?

因为有人在主键列创建NOT NULL约束明确。

让我们来看看。

单主键

SQL> create table t(a number primary key); 

Table created. 

SQL> SELECT a.table_name, 
    2 b.column_name, 
    3 a.constraint_type, 
    4 b.position 
    5 FROM user_constraints a 
    6 JOIN user_cons_columns b 
    7 ON a.owner    = b.owner 
    8 AND a.constraint_name = b.constraint_name 
    9 AND a.table_name  = b.table_name 
10 AND a.constraint_type IN ('P', 'C'); 

TABLE_NAME COLUMN_NAM C POSITION 
---------- ---------- - ---------- 
T   A   P   1 

复合主键

SQL> drop table t purge; 

Table dropped. 

SQL> create table t(a number, b number); 

Table created. 

SQL> alter table t add constraint t_pk PRIMARY KEY(a, 

Table altered. 

SQL> SELECT a.table_name, 
    2 b.column_name, 
    3 a.constraint_type, 
    4 b.position 
    5 FROM user_constraints a 
    6 JOIN user_cons_columns b 
    7 ON a.owner    = b.owner 
    8 AND a.constraint_name = b.constraint_name 
    9 AND a.table_name  = b.table_name 
10 AND a.constraint_type IN ('P', 'C'); 

TABLE_NAME COLUMN_NAM C POSITION 
---------- ---------- - ---------- 
T   A   P   1 
T   B   P   2 

主键和NOT NULL

SQL> drop table t purge; 

Table dropped. 

SQL> create table t(a number primary key not null); 

Table created. 

SQL> SELECT a.table_name, 
    2 b.column_name, 
    3 a.constraint_type, 
    4 b.position 
    5 FROM user_constraints a 
    6 JOIN user_cons_columns b 
    7 ON a.owner    = b.owner 
    8 AND a.constraint_name = b.constraint_name 
    9 AND a.table_name  = b.table_name 
10 AND a.constraint_type IN ('P', 'C'); 

TABLE_NAME COLUMN_NAM C POSITION 
---------- ---------- - ---------- 
T   A   C 
T   A   P   1 
+0

什么是_leading column_它有什么作用(如果有的话)? – monster

+0

“领先专栏”我指的是在这方面的第一栏。但是,它在连接(复合)索引中具有重要意义。它超出了你的问题的范围。不过,如果您有兴趣,请浏览http://www.orafaq.com/tuningguide/concatenated%20indexes.html –