欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql中的主外键实例 博客分类: sql MySQL 

程序员文章站 2024-02-20 16:48:04
...

mysql中如果要设置主外键关联的话,其数据库的类型必须市INNODB类型的;

自己练习时给个示例:

CREATE TABLE Department( 
    DepartmentId int(11)  NOT  NULL  AUTO_INCREMENT ,
    部門 varchar(30),
      CONSTRAINT Department_pk PRIMARY KEY (DepartmentId)
) TYPE=INNODB CHARACTER SET utf8 COLLATE utf8_unicode_ci;

insert into Department(部門) values('销售部')
insert into Department(部門) values('开发部')

CREATE  TABLE Employee(
    EmployeeId int(11)  NOT  NULL  AUTO_INCREMENT ,
    LastName varchar(30) ,
    --外键一定是要定义索引,且它一定是int或integer类型
    DepartmentID int(11),
    --这里只是定义主索引,constranit是约束的意思
    CONSTRAINT Employee_pk PRIMARY  KEY ( EmployeeId ),
    INDEX (DepartmentID)
) TYPE=INNODB CHARACTER SET utf8 COLLATE utf8_unicode_ci;
insert into Employee(`DepartmentID`,`LastName`) values(1,'keith')
insert into Employee(`DepartmentID`,`LastName`) values(2,'given')
insert into Employee(`DepartmentID`,`LastName`) values(1,'scach')
insert into Employee(`DepartmentID`,`LastName`) values(2,'tom')

 

相关标签: MySQL