SQL語法基礎之CREATE語句
作者:尹正傑
版權聲明:原創作品,謝絕轉載!否則將追究法律責任。
一.查看幫助信息
1>.使用“?”來查看MySQL命令的幫助信息
mysql> ? CREATE #這里告訴我們CREATE命令需要和那些命令一起使用 Many help items for your request exist. To make a more specific request, please type 'help <item>', where <item> is one of the following topics: CREATE DATABASE CREATE EVENT CREATE FUNCTION CREATE FUNCTION UDF CREATE INDEX CREATE PROCEDURE CREATE RESOURCE GROUP CREATE ROLE CREATE SERVER CREATE SPATIAL REFERENCE SYSTEM CREATE TABLE CREATE TABLESPACE CREATE TRIGGER CREATE USER CREATE VIEW SHOW SHOW CREATE DATABASE SHOW CREATE EVENT SHOW CREATE FUNCTION SHOW CREATE PROCEDURE SHOW CREATE TABLE SHOW CREATE USER SPATIAL mysql>
2>.查看CREATE DATABASE命令的幫助信息
mysql> ? CREATE DATABASE Name: 'CREATE DATABASE' Description: Syntax: CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification] ... create_specification: [DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_name CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE. URL: http://dev.mysql.com/doc/refman/8.0/en/create-database.html #這里是官方給的幫助文檔 mysql>
3>.查詢幫助時關鍵點剖析
剛剛學習MySQL的小伙伴,可能知道使用問好(“?”)可以查詢命令的使用方法,但是獲取到幫助信息后,看不懂該怎么用。別着急,我們把幫助信息細細的揣摩一下就明白咋用了,也方便我在下面執行相應的SQL語句時,大家不會產生過多歧義。首先我們以上面的查看“CREATE DATABASE”命令的幫助信息為例,簡要說明一下該如何查看幫助信息:
第一:沒有使用括號包裹起來的字段是必須寫的。
第二:使用大括號(“{ }”)包裹起來的字段是必須寫的,只不過我們需要從大括號中用管道(“|”)分隔的各個字段中選取相應一個來使用,例如“{DATABASE | SCHEMA}” 就表示我們必須選一個字段,要么選擇DATABASE,要么選擇SCHEME,不可以不選喲!
第三:中括號的字段是可以不寫的,比如“[IF NOT EXISTS] ”這個語句咱們就是可以不寫,不過建議大家寫上,可以避免出錯,它是一個IF判斷語句。
二.CREATE DATABASE
1>.CREATE DATABASE 語句是在MySQL實力上創建一個指定名稱的數據庫,CREATE SCHEMA語句的語意和CREATE DATABASE是一樣的。
mysql> ? CREATE DATABASE Name: 'CREATE DATABASE' Description: Syntax: CREATE {DATABASE | SCHEMA} [IF NOT EXISTS] db_name [create_specification] ... create_specification: [DEFAULT] CHARACTER SET [=] charset_name | [DEFAULT] COLLATE [=] collation_name CREATE DATABASE creates a database with the given name. To use this statement, you need the CREATE privilege for the database. CREATE SCHEMA is a synonym for CREATE DATABASE. URL: http://dev.mysql.com/doc/refman/8.0/en/create-database.html mysql>
2>.當創建當數據本身存在沒有寫明“IF NOT EXISTS”子句是,創建數據庫當語句會報錯
3>.create_specification子句指明創建數據庫的屬性,並且存儲在db.opt文件中
• Character set屬性指明此數據庫的默認字符集
• Collate屬性指明此數據庫的默認排序規則
4>.創建后的數據庫在數據文件中所在目錄會創建一個子句的文件目錄,用來包含后續創建的表文件。
5>.創建數據庫案例展示

mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 4 rows in set (0.00 sec) mysql> mysql> CREATE DATABASE yinzhengjie CHARACTER SET = utf8; Query OK, 1 row affected, 1 warning (0.01 sec) mysql> mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | yinzhengjie | +--------------------+ 5 rows in set (0.00 sec) mysql> mysql> SHOW CREATE DATABASE yinzhengjie; +-------------+----------------------------------------------------------------------+ | Database | Create Database | +-------------+----------------------------------------------------------------------+ | yinzhengjie | CREATE DATABASE `yinzhengjie` /*!40100 DEFAULT CHARACTER SET utf8 */ | +-------------+----------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql>

mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | yinzhengjie | +--------------------+ 5 rows in set (0.00 sec) mysql> mysql> SHOW CREATE DATABASE yinzhengjie; +-------------+----------------------------------------------------------------------+ | Database | Create Database | +-------------+----------------------------------------------------------------------+ | yinzhengjie | CREATE DATABASE `yinzhengjie` /*!40100 DEFAULT CHARACTER SET utf8 */ | +-------------+----------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql> mysql> CREATE DATABASE yinzhengjie CHARACTER SET = gbk; ERROR 1007 (HY000): Can't create database 'yinzhengjie'; database exists mysql> mysql> CREATE DATABASE IF NOT EXISTS yinzhengjie CHARACTER SET = gbk; Query OK, 1 row affected, 1 warning (0.00 sec) mysql> mysql> SHOW CREATE DATABASE yinzhengjie; +-------------+----------------------------------------------------------------------+ | Database | Create Database | +-------------+----------------------------------------------------------------------+ | yinzhengjie | CREATE DATABASE `yinzhengjie` /*!40100 DEFAULT CHARACTER SET utf8 */ | +-------------+----------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql>
溫馨提示:
在MySQL5.7版本咱們也可以直接通過mkdir的操作系統命令在數據目錄創建文件夾,則MySQL會識別為一個數據庫,並在執行show databases命令時可以看到。
但是,在MySQL8.0版本咱們再通過mkdir的操作系統命令在數據目錄創建文件夾,就不會被識別了喲!
三.CREATE TABLE
1>.查看CREATE TABLE的幫助信息
mysql> ? CREATE TABLE Name: 'CREATE TABLE' Description: Syntax: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) [table_options] [partition_options] CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name [(create_definition,...)] [table_options] [partition_options] [IGNORE | REPLACE] [AS] query_expression CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name { LIKE old_tbl_name | (LIKE old_tbl_name) } create_definition: col_name column_definition | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (key_part,...) [index_option] ... | {INDEX|KEY} [index_name] [index_type] (key_part,...) [index_option] ... | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (key_part,...) [index_option] ... | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (key_part,...) [index_option] ... | [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (col_name,...) reference_definition | CHECK (expr) column_definition: data_type [NOT NULL | NULL] [DEFAULT {literal | (expr)} ] [AUTO_INCREMENT] [UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT 'string'] [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}] [reference_definition] | data_type [GENERATED ALWAYS] AS (expression) [VIRTUAL | STORED] [NOT NULL | NULL] [UNIQUE [KEY]] [[PRIMARY] KEY] [COMMENT 'string'] data_type: (see http://dev.mysql.com/doc/refman/8.0/en/data-types.html) key_part: {col_name [(length)] | (expr)} [ASC | DESC] index_type: USING {BTREE | HASH} index_option: KEY_BLOCK_SIZE [=] value | index_type | WITH PARSER parser_name | COMMENT 'string' | {VISIBLE | INVISIBLE} reference_definition: REFERENCES tbl_name (key_part,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option] reference_option: RESTRICT | CASCADE | SET NULL | NO ACTION | SET DEFAULT table_options: table_option [[,] table_option] ... table_option: AUTO_INCREMENT [=] value | AVG_ROW_LENGTH [=] value | [DEFAULT] CHARACTER SET [=] charset_name | CHECKSUM [=] {0 | 1} | [DEFAULT] COLLATE [=] collation_name | COMMENT [=] 'string' | COMPRESSION [=] {'ZLIB'|'LZ4'|'NONE'} | CONNECTION [=] 'connect_string' | {DATA|INDEX} DIRECTORY [=] 'absolute path to directory' | DELAY_KEY_WRITE [=] {0 | 1} | ENCRYPTION [=] {'Y' | 'N'} | ENGINE [=] engine_name | INSERT_METHOD [=] { NO | FIRST | LAST } | KEY_BLOCK_SIZE [=] value | MAX_ROWS [=] value | MIN_ROWS [=] value | PACK_KEYS [=] {0 | 1 | DEFAULT} | PASSWORD [=] 'string' | ROW_FORMAT [=] {DEFAULT|DYNAMIC|FIXED|COMPRESSED|REDUNDANT|COMPACT} | STATS_AUTO_RECALC [=] {DEFAULT|0|1} | STATS_PERSISTENT [=] {DEFAULT|0|1} | STATS_SAMPLE_PAGES [=] value | TABLESPACE tablespace_name | UNION [=] (tbl_name[,tbl_name]...) partition_options: PARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY [ALGORITHM={1|2}] (column_list) | RANGE{(expr) | COLUMNS(column_list)} | LIST{(expr) | COLUMNS(column_list)} } [PARTITIONS num] [SUBPARTITION BY { [LINEAR] HASH(expr) | [LINEAR] KEY [ALGORITHM={1|2}] (column_list) } [SUBPARTITIONS num] ] [(partition_definition [, partition_definition] ...)] partition_definition: PARTITION partition_name [VALUES {LESS THAN {(expr | value_list) | MAXVALUE} | IN (value_list)}] [[STORAGE] ENGINE [=] engine_name] [COMMENT [=] 'string' ] [DATA DIRECTORY [=] 'data_dir'] [INDEX DIRECTORY [=] 'index_dir'] [MAX_ROWS [=] max_number_of_rows] [MIN_ROWS [=] min_number_of_rows] [TABLESPACE [=] tablespace_name] [(subpartition_definition [, subpartition_definition] ...)] subpartition_definition: SUBPARTITION logical_name [[STORAGE] ENGINE [=] engine_name] [COMMENT [=] 'string' ] [DATA DIRECTORY [=] 'data_dir'] [INDEX DIRECTORY [=] 'index_dir'] [MAX_ROWS [=] max_number_of_rows] [MIN_ROWS [=] min_number_of_rows] [TABLESPACE [=] tablespace_name] query_expression: SELECT ... (Some valid select or union statement) CREATE TABLE creates a table with the given name. You must have the CREATE privilege for the table. By default, tables are created in the default database, using the InnoDB storage engine. An error occurs if the table exists, if there is no default database, or if the database does not exist. For information about the physical representation of a table, see http://dev.mysql.com/doc/refman/8.0/en/create-table-files.html. URL: http://dev.mysql.com/doc/refman/8.0/en/create-table.html mysql>
2>.基本的建表語句

mysql> mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | yinzhengjie | +--------------------+ 5 rows in set (0.00 sec) mysql> mysql> USE yinzhengjie; Database changed mysql> mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> CREATE TABLE student(stu_id int,stu_name varchar(30)); Query OK, 0 rows affected (0.01 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | +-----------------------+ 1 row in set (0.00 sec) mysql> mysql> DESC student; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | stu_id | int(11) | YES | | NULL | | | stu_name | varchar(30) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql>

[root@node110 ~]# mysql -uroot -pyinzhengjie mysql: [Warning] Using a password on the command line interface can be insecure. Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 11 Server version: 8.0.14 MySQL Community Server - GPL Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | | yinzhengjie | +--------------------+ 5 rows in set (0.00 sec) mysql> mysql> CREATE TABLE IF NOT EXISTS yinzhengjie.student2(stu_id int,stu_name varchar(30)); Query OK, 0 rows affected (0.01 sec) mysql> mysql> SELECT DATABASE(); +------------+ | DATABASE() | +------------+ | NULL | +------------+ 1 row in set (0.00 sec) mysql> mysql> USE yinzhengjie Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | +-----------------------+ 2 rows in set (0.00 sec) mysql> DESC student2; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | stu_id | int(11) | YES | | NULL | | | stu_name | varchar(30) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql>
3>.TEMPORARY
注意,TEMPORARY關鍵字表示創建的是臨時表,臨時表僅對本鏈接可見,另外的數據庫鏈接不可見,當本鏈接斷開時,臨時表也被自動DROP掉。

mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | +-----------------------+ 2 rows in set (0.00 sec) mysql> mysql> CREATE TEMPORARY TABLE student_temp(stu_tem_id int,stu_tem_name varchar(30)); #這里我們使用TEMPORARY關鍵字創建了一張臨時表 Query OK, 0 rows affected (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | +-----------------------+ 2 rows in set (0.00 sec) mysql> INSERT INTO student_temp VALUES(1,'jason'); #我們往臨時表中插入一條數據 Query OK, 1 row affected (0.00 sec) mysql> mysql> SELECT * FROM student_temp; #很顯然,數據往臨時表中插入成功了,注意,如果此時另一個數據庫鏈接在相同當數據庫執行相同當查詢語句是查不到數據當喲!能查詢的僅限當前的數據庫鏈接! +------------+--------------+ | stu_tem_id | stu_tem_name | +------------+--------------+ | 1 | jason | +------------+--------------+ 1 row in set (0.00 sec) mysql> mysql>quit Bye [root@node110 ~]# mysql -uroot -pyinzhengjie mysql: [Warning] Using a password on the command line interface can be insecure. Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 12 Server version: 8.0.14 MySQL Community Server - GPL Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. mysql> USE yinzhengjie Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> SELECT * FROM student_temp; #很顯然,當創建臨時表當那個數據庫鏈接端口后再鏈接,臨時表已經不存在了! ERROR 1146 (42S02): Table 'yinzhengjie.student_temp' doesn't exist mysql> mysql>
4>.LIKE
LIKE關鍵字表示基於另外一個表的定義復制一個新的空表,空表時尚的字段屬性和索引都和原表相同。

mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | +-----------------------+ 2 rows in set (0.00 sec) mysql> mysql> CREATE TABLE student3 LIKE student2; #咱們這里使用了LIKE關鍵字 Query OK, 0 rows affected (0.01 sec) mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | +-----------------------+ 3 rows in set (0.00 sec) mysql> DESC student2; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | stu_id | int(11) | YES | | NULL | | | stu_name | varchar(30) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> mysql> DESC student3; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | stu_id | int(11) | YES | | NULL | | | stu_name | varchar(30) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql>

mysql> SHOW CREATE TABLE student2; +----------+---------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------+---------------------------------------------------------------------------------------------------------------------------------------+ | student2 | CREATE TABLE `student2` ( `stu_id` int(11) DEFAULT NULL, `stu_name` varchar(30) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +----------+---------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW CREATE TABLE student3; +----------+---------------------------------------------------------------------------------------------------------------------------------------+ | Table | Create Table | +----------+---------------------------------------------------------------------------------------------------------------------------------------+ | student3 | CREATE TABLE `student3` ( `stu_id` int(11) DEFAULT NULL, `stu_name` varchar(30) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 | +----------+---------------------------------------------------------------------------------------------------------------------------------------+ 1 row in set (0.00 sec) mysql>
5>.CREATE TABLE ... AS SELECT 語句
表示創建表的同時將SELECT的查詢結果數據插入到表中,但索引和主外鍵信息都不會同步過來

mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | +-----------------------+ 3 rows in set (0.00 sec) mysql> mysql> SELECT * FROM student; +--------+-------------+ | stu_id | stu_name | +--------+-------------+ | 1 | jason | | 2 | danny | | 3 | jenny | | 4 | liming | | 5 | yinzhengjie | +--------+-------------+ 5 rows in set (0.00 sec) mysql> mysql> CREATE TABLE student4 AS SELECT * FROM student; Query OK, 5 rows affected (0.01 sec) Records: 5 Duplicates: 0 Warnings: 0 mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | +-----------------------+ 4 rows in set (0.00 sec) mysql> mysql> SELECT * FROM student4; +--------+-------------+ | stu_id | stu_name | +--------+-------------+ | 1 | jason | | 2 | danny | | 3 | jenny | | 4 | liming | | 5 | yinzhengjie | +--------+-------------+ 5 rows in set (0.00 sec) mysql>
6>.INNORE和REPLACE
表示在插入數據的過程中如果新表中碰到違反唯一約束的情況下怎么處理,IGNORE表示不插入,REPLACE表示替換已有的數據,默認兩個關鍵字都不寫則碰到違反的情況會報錯。
7>.DATA_TYPE
表示定義字段類型
8>.NOT NULL/NULL
表示字段是否允許為空,默認NULL表示允許為空,NOT NULL表示需要對此字段明確數值,或者要有默認值,否則報錯。

mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | +-----------------------+ 4 rows in set (0.00 sec) mysql> mysql> CREATE TABLE student5(stu_id INT NOT NULL,stu_name VARCHAR(50)); Query OK, 0 rows affected (0.02 sec) mysql> mysql> INSERT INTO student5(stu_name) values('jason'); #這里報錯是正確的,因為我們要求stu_id字段不允許為空,我們又沒有給他指定自增屬性,因此需要手動給該字段賦值! ERROR 1364 (HY000): Field 'stu_id' doesn't have a default value mysql> mysql> INSERT INTO student5(stu_id,stu_name) values(001,'jason'); Query OK, 1 row affected (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | | student5 | +-----------------------+ 5 rows in set (0.00 sec) mysql> mysql> SELECT * FROM student5; +--------+----------+ | stu_id | stu_name | +--------+----------+ | 1 | jason | +--------+----------+ 1 row in set (0.00 sec) mysql>
9>.DEFAULT
表示設置字段的默認值

mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | | student5 | +-----------------------+ 5 rows in set (0.00 sec) mysql> mysql> CREATE TABLE student6(stu_id INT,stu_name varchar(50),stu_gender ENUM('boy','girl') DEFAULT 'boy'); Query OK, 0 rows affected (0.01 sec) mysql> mysql> INSERT INTO student6 VALUES(001,'yinzhengjie',DEFAULT); Query OK, 1 row affected (0.01 sec) mysql> mysql> INSERT INTO student6 VALUES(002,'Jenny','girl'); Query OK, 1 row affected (0.00 sec) mysql> mysql> INSERT INTO student6(stu_id,stu_name) VALUES(003,'Danny'); Query OK, 1 row affected (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | | student5 | | student6 | +-----------------------+ 6 rows in set (0.00 sec) mysql> SELECT * FROM student6; +--------+-------------+------------+ | stu_id | stu_name | stu_gender | +--------+-------------+------------+ | 1 | yinzhengjie | boy | | 2 | Jenny | girl | | 3 | Danny | boy | +--------+-------------+------------+ 3 rows in set (0.00 sec) mysql>
10>.COLUMN_FORMAT
目前僅在ndb存儲引擎的表上有用,表示該字段的存儲類型是FIXED,DYNAMIC或者DEFAULT。
11>.STORAGE
目前也僅在ndb存儲引擎的表上有用。
12>.CONSTRAINT
表示為主鍵,唯一鍵,外鍵等約束條件命名,如果沒有命名則MySQL會默認給一個。
13>.PRIMARY KEY
表示該字段為主鍵,主鍵字段必須唯一,必須非空,一個表中只能有一個主鍵,主鍵可以包含一個或者多個字段。
14>.KEY/INDEX
表示索引字段。
15>.UNIQUE
表示該字段為唯一屬性字段,且允許包含多個NULL值。
16>.FOREIGN KEY
表示該字段為外鍵字段。一個表中的 FOREIGN KEY 指向另一個表中的 PRIMARY KEY。
17>.AUTO_INCREMENT
表示字段為整數或者浮點數類型的value+1遞增數值,value為當前表中該字段最大的值,默認是從1開始遞增;一個表中只允許有一個自增字段,且該字段必須有key屬性,不能還有DEFAULT屬性,且插入復制會被當成很大的整數。

mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | | student5 | | student6 | +-----------------------+ 6 rows in set (0.00 sec) mysql> mysql> CREATE TABLE student7(stu_id INT PRIMARY KEY AUTO_INCREMENT,stu_name VARCHAR(30)); Query OK, 0 rows affected (0.01 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | | student5 | | student6 | | student7 | +-----------------------+ 7 rows in set (0.00 sec) mysql> mysql> INSERT INTO student7(stu_name) VALUES('yinzhengjie'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO student7(stu_id,stu_name) VALUES(5,'jason'); Query OK, 1 row affected (0.01 sec) mysql> INSERT INTO student7(stu_name) VALUES('jenny'); Query OK, 1 row affected (0.01 sec) mysql> mysql> SELECT * FROM student7; +--------+-------------+ | stu_id | stu_name | +--------+-------------+ | 1 | yinzhengjie | | 5 | jason | | 6 | jenny | +--------+-------------+ 3 rows in set (0.00 sec) mysql>

mysql> SELECT DATABASE(); +-------------+ | DATABASE() | +-------------+ | yinzhengjie | +-------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | student | | student2 | | student3 | | student4 | | student5 | | student6 | | student7 | +-----------------------+ 7 rows in set (0.01 sec) mysql> mysql> CREATE TABLE gender( -> gender_id INT(11) NOT NULL, -> name VARCHAR(30) DEFAULT NULL, -> PRIMARY KEY(gender_id) -> ); Query OK, 0 rows affected (0.01 sec) mysql>

mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | gender | | student | | student2 | | student3 | | student4 | | student5 | | student6 | | student7 | +-----------------------+ 8 rows in set (0.00 sec) mysql> mysql> CREATE TABLE student8( -> stu_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, -> stu_name VARCHAR(50) UNIQUE, -> gender INT, -> CONSTRAINT waijian_01 FOREIGN KEY(gender) REFERENCES gender(gender_id) -> ); Query OK, 0 rows affected (0.01 sec) mysql> SHOW TABLES; +-----------------------+ | Tables_in_yinzhengjie | +-----------------------+ | gender | | student | | student2 | | student3 | | student4 | | student5 | | student6 | | student7 | | student8 | +-----------------------+ 9 rows in set (0.00 sec) mysql> mysql> DESC student8; +----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | stu_id | int(11) | NO | PRI | NULL | auto_increment | | stu_name | varchar(50) | YES | UNI | NULL | | | gender | int(11) | YES | MUL | NULL | | +----------+-------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) mysql> mysql> DESC gender; +-----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+-------+ | gender_id | int(11) | NO | PRI | NULL | | | name | varchar(30) | YES | | NULL | | +-----------+-------------+------+-----+---------+-------+ 2 rows in set (0.00 sec) mysql> mysql>
三.小試牛刀
設計一個學生選課數據庫系統
• 創建一個名為course的數據庫
• 在該數據庫下創建以下幾個表:
• Students表:
sid整型自增主鍵,sname字符串64位,gender字符串12位,dept_id整型並外鍵到Dept表的id字段
• Dept表:
id整型自增主鍵,dept_name字符串64位
• Course表:
id整型自增字段主鍵,course_name字符串64位,teacher_id整型外鍵到 Teacher表的id字段
• Teacher表:
id整型自增字段主鍵,name字符串64位,dept_id整型外鍵到Dept表的id 字段
• Students表和teacher表的dept_id為非空
首先,上面這道題很簡單,但是我要勸心急的小伙伴先把真道題讀完了在寫SQL,讀完題之后我們會發現Student表依賴於Dept表,Course表依賴於Teacher表,Tearcher表依賴於Dept表,而這些表都存放在course的數據庫中。分析清楚題意后我們在寫SQL就相對得心應手了,相應的SQL語句如下:

mysql> CREATE DATABASE course CHARACTER SET = utf8; Query OK, 1 row affected, 1 warning (0.00 sec) mysql>

mysql> USE course; Database changed mysql> mysql> CREATE TABLE Dept(id INT PRIMARY KEY AUTO_INCREMENT,demt_name VARCHAR(64)); Query OK, 0 rows affected (0.01 sec) mysql>

mysql> select database(); +------------+ | database() | +------------+ | course | +------------+ 1 row in set (0.00 sec) mysql> mysql> CREATE TABLE students( -> sid INT PRIMARY KEY AUTO_INCREMENT, -> sname VARCHAR(64), -> gender VARCHAR(12), -> dept_id INT NOT NULL, -> CONSTRAINT student_dept FOREIGN KEY(dept_id) REFERENCES Dept(id) -> ); Query OK, 0 rows affected (0.01 sec) mysql>

mysql> SELECT DATABASE(); +------------+ | DATABASE() | +------------+ | course | +------------+ 1 row in set (0.00 sec) mysql> mysql> CREATE TABLE Teacher( -> id INT PRIMARY KEY AUTO_INCREMENT, -> name VARCHAR(64), -> dept_id INT NOT NULL, -> CONSTRAINT teacher_dept FOREIGN KEY(dept_id) REFERENCES Dept(id) -> ); Query OK, 0 rows affected (0.01 sec) mysql>

mysql> SELECT DATABASE(); +------------+ | DATABASE() | +------------+ | course | +------------+ 1 row in set (0.00 sec) mysql> mysql> CREATE TABLE course( -> id INT PRIMARY KEY AUTO_INCREMENT, -> course_name VARCHAR(64), -> teacher_id INT, -> CONSTRAINT course_teacher FOREIGN KEY(teacher_id) REFERENCES Teacher(id) -> ); Query OK, 0 rows affected (0.01 sec) mysql> mysql>
mysql> SELECT DATABASE(); +------------+ | DATABASE() | +------------+ | course | +------------+ 1 row in set (0.00 sec) mysql> mysql> SHOW TABLES; +------------------+ | Tables_in_course | +------------------+ | Dept | | Teacher | | course | | students | +------------------+ 4 rows in set (0.00 sec) mysql> mysql> DESC Dept; +-----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-----------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | demt_name | varchar(64) | YES | | NULL | | +-----------+-------------+------+-----+---------+----------------+ 2 rows in set (0.00 sec) mysql> mysql> DESC Teacher; +---------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(64) | YES | | NULL | | | dept_id | int(11) | NO | MUL | NULL | | +---------+-------------+------+-----+---------+----------------+ 3 rows in set (0.00 sec) mysql> DESC course; +-------------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | course_name | varchar(64) | YES | | NULL | | | teacher_id | int(11) | YES | MUL | NULL | | +-------------+-------------+------+-----+---------+----------------+ 3 rows in set (0.01 sec) mysql> mysql> DESC students; +---------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +---------+-------------+------+-----+---------+----------------+ | sid | int(11) | NO | PRI | NULL | auto_increment | | sname | varchar(64) | YES | | NULL | | | gender | varchar(12) | YES | | NULL | | | dept_id | int(11) | NO | MUL | NULL | | +---------+-------------+------+-----+---------+----------------+ 4 rows in set (0.00 sec) mysql>