2014-03-31 39 views
1

我有一个表,主键的一部分是另一个表的外键。当fk列是pk的子集时,主键索引是否会用作外键的索引?

create table player_result (
    event_id  integer not null, 
    pub_time  timestamp not null, 
    name_key  varchar(128) not null, 
    email_address varchar(128), 
    withdrawn  boolean not null, 
    place   integer, 
    realized_values hstore, 
    primary key (event_id, pub_time, name_key), 
    foreign key (email_address) references email(address), 
    foreign key (event_id, pub_time) references event_publish(event_id, pub_time)); 

将主键足以回到event_idpub_time外键生成的索引?

回答

2

是的。

指数A,B,C

是良好的:

A
A,B
A,B,C(和完整的3场的任何其他组合,如果默认顺序并不重要)

但不适用于其他组合(如B,CC,A等)。

2

这将是参考侧有用,使得在引用DELETEUPDATE可用于参考的行或跑步级联的存在进行检查时所使用的引用侧的PRIMARY KEY作为指标更新/删除。 PostgreSQL不需要这个索引就可以存在,它只是使外键约束检查更快。

它是而不是足以作为对这些列的参考的唯一约束。您无法创建FOREIGN KEYREFERENCES player_result(event_id, pub_time),因为这些列上没有unique约束。只要每一对具有不同的name_key,该对可以在表格中出现多次。

正如@xagyg准确地指出的那样,由外键引用创建的唯一B树索引也仅对索引左侧的列的引用有用。例如,它不能用于查找pub_time, name_key或仅用于name_key