MySQL联合索引用法有哪些?
本文实例讲述了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数据库计有所帮助。
本文地址:http://www.45fan.com/a/question/75244.html