本文实例讲述了mysql联合索引。分享给大家供大家参考,具体如下:
员工表 userid
部门表 deptid
员工部门表
条件:一个员工可以对应多个部门
问题:怎么样设置数据库,让其不能重复添加 userid 和deptid?
uuid userid deptid
111
212
311(这个就不能让其添加)
drop table if exists `dept`;
create table `dept` (
`id` int(11) not null auto_increment,
`deptname` char(32) not null,
primary key (`id`)
) engine=innodb auto_increment=3 default charset=utf8;
-- ----------------------------
-- records of dept
-- ----------------------------
insert into `dept` values ('1', '1');
insert into `dept` values ('2', '2');
drop table if exists `employee`;
create table `employee` (
`id` int(11) not null auto_increment,
`name` varchar(32) not null,
primary key (`id`)
) engine=innodb auto_increment=3 default charset=utf8;
-- ----------------------------
-- records of employee
-- ----------------------------
insert into `employee` values ('1', '11');
drop table if exists `employee_dept`;
create table `employee_dept` (
`id` int(11) not null,
`employeeid` int(11) not null,
`deptid` int(11) not null,
primary key (`id`),
key `bb` (`deptid`),
key `myindex` (`employeeid`,`deptid`),
constraint `aa` foreign key (`employeeid`) references `employee` (`id`),
constraint `bb` foreign key (`deptid`) references `dept` (`id`)
) engine=innodb default charset=utf8;
-- ----------------------------
-- records of employee_dept
-- ----------------------------
insert into `employee_dept` values ('1', '1', '1');
insert into `employee_dept` values ('2', '1', '2');
备注:创建联合索引create index myindex on employee_dept (employeeid,deptid);
希望本文所述对大家mysql数据库计有所帮助。
如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!