Home  >  Article  >  Database  >  MySQL union index usage example_MySQL

MySQL union index usage example_MySQL

WBOY
WBOYOriginal
2016-10-09 08:33:381148browse

This article describes the MySQL joint index with examples. Share it with everyone for your reference, the details are as follows:

Employee table userid
Department table deptid
Employee department table

Conditions: One employee can correspond to multiple departments

Question: How to set up the database so that userid and deptid cannot be added repeatedly?

uuid userid deptid
111
212
311 (This cannot be added)

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');

Note: Create a joint index create index myindex on employee_dept (employeeid,deptid);

Readers who are interested in more MySQL-related content can check out the special topics on this site: "Summary of MySQL Index Operation Skills", "Comprehensive Collection of MySQL Log Operation Skills", "Summary of MySQL Transaction Operation Skills", "Comprehensive Collection of MySQL Stored Procedure Skills", " Summary of MySQL database lock related skills" and "Summary of commonly used MySQL functions"

I hope this article will be helpful to everyone’s MySQL database planning.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn