创建一对一关系的表

  在需要创建具有一对一关系的两张表时,如创建hansband和wife表的时候,两个表里面的个条记录应该

为一对一的关系。因此为了保证这种一对一的关系我们 仍然需要使用外键约束,将wife表里面的主键设置为外

键,引用的对象为hasband表里面的主键。

  则此时wife表里面的主键列,必须满足主键的特征,唯一、非空、引用。因此确保了表中的每一条记录都

唯一的,因此保证了两个表当中的每一条记录都是一一对应的。

SQL语句如下:

hasband table:

    create table hansband(

  hid int primary key auto_increment,

  hname varchar(50)

);

wife table:

    create table wife(

  wid int primary key auto_increment,

  wname varchar(50),

  constraint fk_wife_hasband foreign key(wid) references hasband(hid)

);

猜你喜欢

转载自www.cnblogs.com/wangkaia/p/11994616.html