MySQL-----表的操作
文章目录
- 前言
- 一、创建表
- 二、创建表案例
-
- 使用MyISAM的存储引擎建表
- 使用InnoDB的存储引擎建表
- 三、查看表结构
- 四、修改表
- 五、删除表
- 总结
前言
正文开始!!!
一、创建表
语法:
CREATE TABLE table_name (
field1 datatype,
field2 datatype,
field3 datatype
) character set 字符集 collate 校验规则 engine 存储引擎;
说明:
field
表示列名datatype
表示列的类型character set
字符集,如果没有指定的字符集,以数据库默认的字符集为准collate
检验规则,如果没有指定校验规则,以数据库默认的校验规则为准
二、创建表案例
使用MyISAM的存储引擎建表
mysql> create table if not exists users(-> id int comment '用户的id',-> name varchar(20) comment '用户的姓名',-> password varchar(30) comment '用户的登录密码',-> birthday date comment '用户的生日'-> )character set utf8 collate utf8_general_ci engine MyISAM;
Query OK, 0 rows affected (0.00 sec)
使用InnoDB的存储引擎建表
mysql> create table if not exists students(-> name varchar(20),-> age int,-> number varchar(12),-> sex char(1)-> )engine=Innodb default charset=utf8;
Query OK, 0 rows affected (0.01 sec)
从以上示例我们可以看出使用MyISAM存储引擎对于物理存储中的三个文件.
使用InnoDB存储引擎对于物理存储中的二个文件.
三、查看表结构
desc 表名;
查看详细表属性
show create table users\\G
四、修改表
在项目实际开发中,经常修改某个表的结构,比如字段名字,字段大小,字段类型,表的字符集类型,表的存储引擎等等.我们还有需求,添加字段,删除字段等等.这是我们就需要修改表.
ALTER TABLE tablename ADD (column datatype [DEFAULT expr][,columndatatype]...);ALTER TABLE tablename MODIfy (column datatype [DEFAULT expr][,columndatatype]...);ALTER TABLE tablename DROP (column);
案例:
- 在users表添加而条记录
mysql> insert into users (id,name,password,birthday) values (1,'张三','1234','2000-10-01');
Query OK, 1 row affected (0.00 sec)mysql> insert into users (id,name,password,birthday) values (2,'李四','111','2002-09-23');
Query OK, 1 row affected (0.00 sec)
- 在users表添加一个字段,用于保存用户地址
mysql> alter table users add path varchar(32) comment '用来存放用户的地址' after birthday;
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
注意:
NULL和’ '有区别吗?
NULL是没有! ’ '是一个空串! 两个是有区别的!!!
- 修改name,将其长度改为128
mysql> alter table users modify name varchar(128);
Query OK, 2 rows affected (0.01 sec)
Records: 2 Duplicates: 0 Warnings: 0
- 删除password列
注意:删除字段一定要小心了,删除字段及其对应的列数据都没了.
mysql> alter table users drop password;
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
- 修改表名为employee
mysql> alter table users rename employee;
Query OK, 0 rows affected (0.00 sec)
- 将name列修改为xingming
alter table employee change name xingming varchar(20);---新字段需要完整定义
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
五、删除表
语法格式:
DROP [TEMPORARY] TABLE [IF EXISTS] tbl_name [, tbl_na
实例:
mysql> drop table employee;
Query OK, 0 rows affected (0.00 sec)
总结
(本章完!)