表级约束和列级约束
创建表的语法我在官方的文档中看到了这样的
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...)
1. 上面语法中的create definition可以为是 col_name column_definition,对应下面列举的第一个
create_definition: col_name column_definition | [CONSTRAINT [symbol]] PRIMARY KEY [index_type] (index_col_name,...) [index_option] ... | {INDEX|KEY} [index_name] [index_type] (index_col_name,...) [index_option] ... | [CONSTRAINT [symbol]] UNIQUE [INDEX|KEY] [index_name] [index_type] (index_col_name,...) [index_option] ... | {FULLTEXT|SPATIAL} [INDEX|KEY] [index_name] (index_col_name,...) [index_option] ... | [CONSTRAINT [symbol]] FOREIGN KEY [index_name] (index_col_name,...) reference_definition | CHECK (expr)
1中col_name column_definition的column_definition 可以是[reference_definition],对应下面列举的最后一个
column_definition: data_type [NOT NULL | NULL] [DEFAULT default_value] [AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY] [COMMENT 'string'] [COLUMN_FORMAT {FIXED|DYNAMIC|DEFAULT}] [STORAGE {DISK|MEMORY|DEFAULT}] [reference_definition]
2中的[reference_definition]可以使用下面的语法
reference_definition: REFERENCES tbl_name (index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option]
那么问题来了我这么写为什么不行?t1已经定义了和t2相同的结构
CREATE TABLE t2(
id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT,
username VARCHAR(20) REFERENCES t1(username)
);
create_definition: col_name column_definition
username VARCHAR(20) REFERENCES t1(username) 对应 create_definition
username 对应 col_name
VARCHAR(20) REFERENCES t1(username) 对应column_definition
column_definition: data_type [reference_definition]
VARCHAR(20) 对应 data_type
REFERENCES t1(username) 对应 [reference_definition]
reference_definition对应如下的语法。
reference_definition: REFERENCES tbl_name (index_col_name,...) [MATCH FULL | MATCH PARTIAL | MATCH SIMPLE] [ON DELETE reference_option] [ON UPDATE reference_option]
最后再问一下,外键约束有几种声明方式,表级约束和列级约束还是没搞懂,老师说的那个可以在列定义时声明,也可以在列定以后声明,什么是定义时,什么是定以后?
例如:
CREATE TABLE t2(
-> id TINYINT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
-> name VARCHAR(10) NOT NULL,
-> pid TINYINT UNSIGNED ,
-> FOREIGN KEY(pid) REFERENCES t1(id)
-> );
这个是定以时还是定以后?定义时是写在一个语句中还是在一个括号中?老师说的NOT NULL 和 DEFAULT约束只能是列级约束,意思是只能在一条语句中连着写,比如name VARCHAR(10) NOT NULL?