Last active
July 12, 2019 09:27
-
-
Save matteocollina/84e0e5b6f9da79f188bef3c20f521873 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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