Skip to content

Instantly share code, notes, and snippets.

@matteocollina
Last active July 12, 2019 09:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matteocollina/84e0e5b6f9da79f188bef3c20f521873 to your computer and use it in GitHub Desktop.
Save matteocollina/84e0e5b6f9da79f188bef3c20f521873 to your computer and use it in GitHub Desktop.
CREATE TABLE `Student`
(
`idStudent` int NOT NULL auto_increment,
`name` varchar(45) NOT NULL ,
PRIMARY KEY (`idStudent`)
);
CREATE TABLE `Exam`
(
`idExam` int NOT NULL auto_increment,
`name` varchar(45) NOT NULL ,
PRIMARY KEY (`idExam`)
);
/*
TEST 1
Error Code: 1075. Incorrect table definition;
there can be only one auto column and it must be defined as a key
*/
CREATE TABLE `StudentExams`
(
`idStudentExams` int NOT NULL auto_increment,
`idStudent` int NOT NULL ,
`idExam` int NOT NULL ,
FOREIGN KEY (`idStudent`) REFERENCES `Student` (`idStudent`),
FOREIGN KEY (`idExam`) REFERENCES `Exam` (`idExam`),
PRIMARY KEY (`idStudent`,`idExam`)
);
/*
TEST 2
Unique multiple columns
NB. It doesn't work if a column is NULL, so you can insert multiple rows with those values
*/
CREATE TABLE `StudentExams`
(
`idStudentExams` int NOT NULL auto_increment,
`idStudent` int NOT NULL ,
`idExam` int NOT NULL ,
PRIMARY KEY (`idStudentExams`),
FOREIGN KEY (`idStudent`) REFERENCES `Student` (`idStudent`),
FOREIGN KEY (`idExam`) REFERENCES `Exam` (`idExam`)
);
ALTER TABLE `StudentExams` ADD UNIQUE `unique_index`(`idStudent`, `idExam`);
INSERT INTO `Student` (`name`) VALUES ('Mario');
INSERT INTO `Exam` (`name`) VALUES ('Biology');
INSERT INTO `StudentExams` (`idStudent`, `idExam`) VALUES ('1', '1');
INSERT INTO `StudentExams` (`idStudent`, `idExam`) VALUES ('1', '1'); /* ERROR 1062: 1062: Duplicate entry '1-1' for key 'unique_index' */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment