一段完整的創建表格的SQL代碼
使用SQL語句創建一張表,不僅可以可以快速熟悉SQL語句,還可以從這看出一個人對該技能點的熟悉程度。
這里先說明幾點:
PRIMARY KEY:主鍵,一張表中只允許有一個PRIMARY KEY,不允許有NULL值。
UNIQUE KEY:約束,約束確保在非主鍵列中不輸入重復的值,允許有NULL值,而PRIMARY KEY 不允許有NULL值,且一張表中只有一個PRIMARY KEY,而UNIQUE KEY在一張表中可以有多個。
ENGINE=INNODB,表示SQL數據庫引擎為INNODB,操作數據庫級別為表中的行級別(可以並發操作兩行不同的數據庫),另外一個引擎為MYISAM,操作數據庫級別為整張表,相對來說,MYISAM操作的效率高於INNODB,不過一般數據庫中都使用的是INNODB。
-- 如果test數據庫不存在,就創建test數據庫: CREATE DATABASE IF NOT EXISTS test; -- 切換到test數據庫 USE test; -- 刪除classes表和students表(如果存在): DROP TABLE IF EXISTS classes; DROP TABLE IF EXISTS students; -- 創建classes表: CREATE TABLE classes ( id BIGINT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- 創建students表: CREATE TABLE students ( id BIGINT NOT NULL AUTO_INCREMENT, class_id BIGINT NOT NULL, name VARCHAR(100) NOT NULL, gender VARCHAR(1) NOT NULL, score INT NOT NULL, PRIMARY KEY (id) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- 插入classes記錄: INSERT INTO classes(id, name) VALUES (1, '一班'); INSERT INTO classes(id, name) VALUES (2, '二班'); INSERT INTO classes(id, name) VALUES (3, '三班'); INSERT INTO classes(id, name) VALUES (4, '四班'); -- 插入students記錄: INSERT INTO students (id, class_id, name, gender, score) VALUES (1, 1, '小明', 'M', 90); INSERT INTO students (id, class_id, name, gender, score) VALUES (2, 1, '小紅', 'F', 95); INSERT INTO students (id, class_id, name, gender, score) VALUES (3, 1, '小軍', 'M', 88); INSERT INTO students (id, class_id, name, gender, score) VALUES (4, 1, '小米', 'F', 73); INSERT INTO students (id, class_id, name, gender, score) VALUES (5, 2, '小白', 'F', 81); INSERT INTO students (id, class_id, name, gender, score) VALUES (6, 2, '小兵', 'M', 55); INSERT INTO students (id, class_id, name, gender, score) VALUES (7, 2, '小林', 'M', 85); INSERT INTO students (id, class_id, name, gender, score) VALUES (8, 3, '小新', 'F', 91); INSERT INTO students (id, class_id, name, gender, score) VALUES (9, 3, '小王', 'M', 89); INSERT INTO students (id, class_id, name, gender, score) VALUES (10, 3, '小麗', 'F', 85); -- OK: SELECT 'ok' as 'result:';
