SQL code to create a table for a complete
Create a table using SQL statements, not only can quickly become familiar with SQL statements, you can see that from a person familiar with the degree of skill points.
First a couple of points here:
PRIMARY KEY: primary key, a table allows only a PRIMARY KEY, NULL values are not allowed.
UNIQUE KEY: constraint constraint ensures that the value of the non-primary key column not enter duplicate, allow NULL value, PRIMARY KEY does not allow NULL values, and a table is only a PRIMARY KEY, and UNIQUE KEY may be a plurality in a table .
ENGINE = INNODB, expressed as SQL database engine INNODB, row level database operation level (which may be concurrent operation of two different rows database) table, another MYISAM engines, the operation of the entire database table level, relatively speaking, MYISAM operating efficiency is higher than INNODB, but most of the database are using INNODB.
- If the test database does not exist, create a test database: the CREATE DATABASE IF the NOT EXISTS test; - switch to test database the USE test; - delete classes and students table table (if present): DROP TABLE IF EXISTS classes; DROP TABLE IF EXISTS Students; - create classes table: the cREATE tABLE classes ( the above mentioned id BIGINT the NOT NULL AUTO_INCREMENT, name VARCHAR ( 100 ) the NOT NULL , PRIMARY KEY (the above mentioned 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:';