在MySQL中,我們可以使用系別對數據庫中的數據進行分類管理。系別的作用在于將數據庫中的所有表按照某一個條件分成若干個組別,從而方便數據的管理和查詢。下面我們就來了解一下MySQL中系別的代碼怎么寫。
CREATE DATABASE mydb; USE mydb; CREATE TABLE students ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, sex CHAR(2) NOT NULL, age INT NOT NULL, dept VARCHAR(30) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE classes ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(20) NOT NULL, teacher VARCHAR(20) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE score ( id INT NOT NULL AUTO_INCREMENT, sid INT NOT NULL, cid INT NOT NULL, score FLOAT NOT NULL, PRIMARY KEY (id), FOREIGN KEY (sid) REFERENCES students(id), FOREIGN KEY (cid) REFERENCES classes(id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE departments ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(30) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; ALTER TABLE students ADD COLUMN dept_id INT NOT NULL DEFAULT 1 AFTER dept; INSERT INTO departments(name) VALUES ('Computer Science'); INSERT INTO departments(name) VALUES ('Electronic Engineering'); UPDATE students SET dept_id = 1 WHERE dept = 'Computer Science'; UPDATE students SET dept_id = 2 WHERE dept = 'Electronic Engineering'; ALTER TABLE students DROP COLUMN dept; ALTER TABLE students CHANGE COLUMN dept_id dept VARCHAR(30) NOT NULL; ALTER TABLE students ADD CONSTRAINT FOREIGN KEY (dept) REFERENCES departments(name); SELECT students.name, score.score, classes.name FROM students JOIN score ON students.id = score.sid JOIN classes ON score.cid = classes.id WHERE students.dept = 'Computer Science' AND score.score >60;
以上是MySQL中系別的相關代碼,首先我們要創建的就是含有系別的表。可以看到,我們創建了一個departments表來存放系別信息,并在students表中加入_dept_id列,用于存放每個學生所屬的系別。接著我們將每個學生對應的系別ID轉換成系別名稱,并將dept_id列的數據類型改為VARCHAR類型。最后,我們在students表中添加了一個外鍵,以確保每個學生所屬的系別在departments表中存在。最后一個SELECT語句用來查詢計算機系成績大于60分的學生信息。