创建表
create table表名(
字段名1 类型[(宽度)] [约束条件] [comment '字段说明'],
字段名2 类型[(宽度)] [约束条件] [comment '字段说明'],
字段名3 类型[(宽度)] [约束条件] [comment '字段说明']
)[表的一些设置];
注意:
1.在同一张表中,字段名不能相同
2.宽度和约束条件为可选参数,字段名和类型是必须的
3.后一个字段后不能加逗号
4.类型是用来限制 字段 必须以何种数据类型来存储记录
5.类型其实也是对字段的约束(约束字段下的记录必须为XX类型)
6.类型后写的 约束条件 是在类型之外的 额外添加的约束
约束说明
not null
标识该字段不能为空
mysql> create table test1(a int not null comment '字段a');
Query OK, 0 rows affected (0.01 sec)
mysql> insert into test1 values (null);
ERROR 1048 (23000): Column 'a' cannot be null
mysql> insert into test1 values (1);
Query OK, 1 row affected (0.00 sec)
mysql> select * from test1;
+---+
| a |
+---+
| 1 |
+---+
1 row in set (0.00 sec)
default value:为该字段设置默认值,默认值为value
mysql> drop table IF EXISTS test2;
Query OK, 0 rows affected (0.01 sec)
mysql> create table test2(
-> a int not null comment '字段a',
-> b int not null default 0 comment '字段b'
-> );
Query OK, 0 rows affected (0.02 sec)
mysql> insert into test2(a) values (1);
Query OK, 1 row affected (0.00 sec)
mysql> select *from test2;
+---+---+
| a | b |
+---+---+
| 1 | 0 |
+---+---+
1 row in set (0.00 sec)
上面插入时未设置b的值,自动取默认值0
primary key
标识该字段为该表的主键,可以唯一的标识记录,插入重复的会报错
两种写法
方式1
跟在列后
如下:
mysql> drop table IF EXISTS test3;
Query OK, 0 rows affected, 1 warning (0.00 sec)
mysql> create table test3(
-> a int not null comment '字段a' primary key