· 6 years ago · Jan 08, 2020, 11:02 AM
1-- DINGEN IN OF UIT COMMENTAAR ZETTEN (OOK MEERDERE LIJNTJES TEGELIJK): CTRL + / (de slash in de numpad boven de 8)
2-- rijen controleren: links in schema rechtermuisknop op tabelnaam: Select Rows: Limit 1000
3-- mogelijk om visueel schema van DB te maken met Database -> Reverse Engineer -> doorklikken
4
5-- CREATE DATABASE MyLilDb;
6-- USE MyLilDb; -- MyLilDb als actieve DB zetten
7
8DROP TABLE Student_test; -- MOET als eerste gedropt worden want hij verwijst naar andere tabellen in zijn foreign key constraint
9DROP TABLE Student;
10DROP TABLE Test;
11
12CREATE TABLE IF NOT EXISTS Student
13(
14 Id INT AUTO_INCREMENT -- indentatie op begin (spatie is genoeg), NOT NULL moet er niet bij want is PK dus sws not null
15,Firstname VARCHAR(100) NOT NULL -- goede gewoonte: we plaatsen kommas opt begin van het lijntje want anders krijgen we constant errormeldingen
16,Lastname VARCHAR(100) NOT NULL
17,Email VARCHAR(100)
18,CreatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP -- handig om in elke tabel te hebben
19-- ,Score INT NOT NULL -- we maken een Test tabel en een Student_Test tussentabel (want veel-op-veel relatie) waar Score zal in komen
20,CONSTRAINT PK_Student PRIMARY KEY(Id) -- kan ook PRIMARY KEY achter Id INT AUTO_INCREMENT zetten, maar dat is niet erg overzichtelijk
21-- ,CONSTRAINT CH_Student_Score CHECK (Score BETWEEN 0 AND 100) -- constraint duidelijke naam geven zodat we weten waarover mogelijke errors gaan
22);
23
24CREATE TABLE IF NOT EXISTS Test
25(
26 Id INT AUTO_INCREMENT
27,Name VARCHAR(100) NOT NULL
28,CreatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP -- handig om in elke tabel te hebben
29,CONSTRAINT PK_Test PRIMARY KEY(Id)
30);
31
32CREATE TABLE IF NOT EXISTS Student_Test
33(
34 StudentId INT
35,TestId INT
36,Score INT NOT NULL
37,CreatedAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP -- handig om in elke tabel te hebben
38,CONSTRAINT PK_Student_Test PRIMARY KEY(StudentId, TestId)
39,CONSTRAINT FK_Student_Test_Student FOREIGN KEY(StudentId) REFERENCES Student(Id)
40,CONSTRAINT FK_Student_Test_Test FOREIGN KEY(TestId) REFERENCES Test(Id)
41,CONSTRAINT CH_Student_Test_Score CHECK (Score BETWEEN 0 AND 100)
42);
43
44INSERT INTO Student(Firstname, Lastname)
45VALUES('Sander', 'Stroobandt');
46
47INSERT INTO Test(Name)
48VALUES('DB1 - EERD');
49
50INSERT INTO Student_Test(StudentId, TestId, Score)
51VALUES(1, 1, 100); -- als je hier een foreign key ingeeft die niet bestaat in de tabel waarnaar hij verwijst zal het een error geven
52
53-- INSERT INTO Student(Firstname, Lastname, Score) -- email moet niet want is nullable, Id is primary key dus wel nodig, maar is auto-generated (AUTO_INCREMENT)
54-- VALUES('Sander', 'Stroobandt', 100); -- zal error geven als je bvb 200 ingeeft (door CHECK CONSTRAINT)
55
56
57-- DROP TABLE Student; -- tabel volledig wegsmijten, voor alsge hem opnieuw wil definieren