创建表时,指定表的结构、数据类型、字符集、校验规则和存储引擎等。以下是创建表的详细语法:
语法:
create table table_name (
field1 datatype [constraint],
field2 datatype [constraint],
...
) [character set charset_name] [collate collation_name] [engine storage_engine];
注:括号[]里面可以省略,自定义写或者不写。
查看表的创建信息:
show create table user;
其中被圈起来的就是我们没有写,默认被添加的。
示例:
create table user (
id int primary key,
name varchar(20) not null comment '用户名',
password char(32) not null comment '密码是32位的md5值',
birthday date comment '生日'
) character set utf8 collate utf8_general_ci engine=myisam;
作用:
users
的表,包含 id
、name
、password
和 birthday
字段。
utf8
,校验规则为 utf8_general_ci
,存储引擎使用 myisam
。
说明:
primary key
:定义主键,确保该字段唯一且不为空。
not null
:字段不能为空。
comment
:给字段加注释,便于理解字段用途。
存储引擎说明:
不同存储引擎具有不同的特性:
语法:
desc 表名;
或者
show columns from table_name;
使用规则:
null
值、键的类型(如 primary key
、index
等)及其他信息。
describe
类似,但输出格式可能略有不同。
示例:
describe user;
语法:
alter table table_name add column column_name datatype
[constraint] [after existing_column];
注:mysql支持分段书写指令
not null
、default
等
使用规则:
示例:
alter table user add assets varchar(100) comment '图片路径' after birthday;
作用:
users
表中添加名为 assets
的字段,用于保存图片路径,数据类型为 varchar(100)
,并放置在 birthday
字段后。
语法:
alter table table_name modify column column_name datatype [constraint];
使用规则:
null
等。
示例:
alter table users modify name varchar(60) not null;
作用:
users
表中 name
字段的长度为 60
,并设置为 not null
。
语法:
alter table table_name drop column column_name;
使用规则:
示例:
drop table user drop asserts;
作用:
user
表中的 asserts 字段。
语法:
alter table table_name change column old_column_name new_column_name datatype [constraint];
not null
、unique
等)
使用规则:
示例:
alter table users change column name xingming varchar(60) not null;
作用:
users
表中的 name
字段重命名为 xingming
,并将数据类型修改为 varchar(60)
,且字段不能为空(not null
)。
语法:
alter table old_table_name rename to new_table_name;
使用规则:
假设我们有一个 users
表,包含以下字段:id
、name
、password
和 birthday
。
1. 插入数据
insert into users (id, name, password, birthday)
values (1, 'a', 'b', '1982-01-04'),
(2, 'b', 'c', '1984-01-04');
2. 查看表结构
describe users;
3. 添加字段:添加 assets
字段,保存图片路径:
alter table users add assets varchar(100) comment '图片路径' after birthday;
4. 修改字段:修改 name
字段的长度:
alter table users modify name varchar(60);
5. 删除字段:删除 password
字段:
alter table users drop password;
6. 修改表名:将表名 users
改为 employee
:
alter table users rename to employee;
7. 最终查看表结构
describe employee;
注:
alter table
命令,可以添加、删除、修改字段,甚至修改表名。
drop table
命令删除表,操作时要格外小心。