日期:2014-05-16  浏览次数:20552 次

数据库:唯一性约束_alternate key(替换键)
数据库:唯一性约束

    所谓唯一性约束(unique constraint)不过是数据表内替代键的另一个名称而已。替代键(alternate key)可以是数据表内不作为主键的其他任何列,只要该键对该数据表唯一即可。换句话说,在唯一列内不允许出现数据重复的现象。比方说,你可以用车辆识别代号(VIN)作为汽车(Automobile)数据表的替代键,在汽车数据表里,主键是汽车识别号(Automobile Identification),这是一种由系统自动生成的ID。你可以在汽车表内对VIN施加唯一性约束,同时再创建一个需要VIN的表。在这个新表内可以声明外键指向汽车表。这样,只要汽车表内有VIN输入数据库就会检验VIN输入结果。这就是保证数据库内数据完整性的另一种有效的措施。

create table parent
    (parent_id int not null,      -- Primary key
    parent_alternate_key int not null,     -- Alternate key
    parent_col1 int null,
    parent_col2 int null,
      constraint pk_parent_id primary key (parent_id),
      constraint ak_parent_alternate_key unique_
       (parent_id, parent_alternate_key)
   

使用约束:
create table child2
    (child2_parent_id int not null,     -- Primary key/Foreign key
    child2_id int not null,     -- Primary key
    child2_col1 int null,
    child2_parent_alternate_key int not null,  -- Foreign key
        constraint pk_child2 primary key (child2_parent_id, child2_id),
        constraint fk_child2_parent foreign key (child2_parent_id)
    references dbo.parent(parent_id),
        constraint fk_pk_ak_child2_parent foreign key _
      (child2_parent_id, child2_parent_alternate_key) _
      references dbo.parent(parent_id, parent_alternate_key)
   


primary key 与UNIQUE的区别
1.一个基本表中只能定义一个primary key,但可以定义多个UNIQUE的约束
2.指定primary key的一个列或多个列的组合都不能为NULL,而UNIQUE所约束的唯一键则允许为空
3.不能为一个列或多个列既定义primary key,又定义UNIQUE约束


MYSQL目前不支持外键,其理由如下:
1.外键使生活更复杂,因为外键的定义必须存储在一个数据库中并且实现他们将破坏使用能被移动、拷贝和删除文件的全部“好方法”。
2.速度影响对INSERT和UPDATE语句是可怕的,并且在这种情况下几乎所有的FOREIGN KEY检查都是无用的,因为不管怎样你通常以正确的顺序在正确的表中插入记录。
3.当更新一张表时,也有在许多表上保存锁的需求,因为副作用可以串联通过全部数据库。首先从一张表中删除记录并且随后从其他表中删除他们,这更快。
4.你再也不可以通过做一个全面的表删除并随后恢复所有的记录的方法来恢复一张表(从新来源或从一个备份)。
5.如果你有外键,你不能倾倒和恢复表,除非你以一个非常特定的做这些。
6.很容易做一个“允许的”的循环定义使得不可能用一个单个create语句重建每一个表,就算定义可行又可用。