MySQL札记6_DDL(数据定义表)

浏览: 1452

在上篇札记MySQL札记5_语句分类(面试考点)归纳了4种常见的MySQL语句。在本篇札记中,主要介绍的是:数据定义语言DDL,data defination language

常用操作

在操作数据表table之前,首先要选择进入某个数据库database:database---table

  • 先进入mysql



    image.png

  • 查看所有的数据库,选择peter数据库进入



    image.png

创建数据表结构

create table 表名(
列名 列类型 关键词,
......
列名 列类型
);
末尾一定要带上逗号

# 创建user表:6种字段+1个主键
mysql>create table user(
id int(10) unsigned not null auto_increment comment 'ID',
user_name varchar(20) not null comment 'user_name',
email varchar(50) not null comment 'user_email',
age tinyint unsigned not null comment 'user_age',
fee decimal(10,2) not null default 0.00 comment 'jiner',
created_at timestamp not null comment 'created_time',
primary key(id)
);

查看数据库的表

show tables;
末尾一定要带上逗号

image.png

查看表结构

desc 表名;
末尾一定要带上逗号

mysql> desc user;
+------------+---------------------+------+-----+-------------------+-----------------------------+
| Field | Type | Null | Key | Default | Extra |
+------------+---------------------+------+-----+-------------------+-----------------------------+
|
id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| user_name | varchar(20) | NO | | NULL | |
|
email | varchar(50) | NO | | NULL | |
| age | tinyint(3) unsigned | NO | | NULL | |
|
fee | decimal(10,2) | NO | | 0.00 | |
| created_at | timestamp | NO | | CURRENT_TIMESTAMP | on update CURRENT_TIMESTAMP |
+------------+---------------------+------+-----+-------------------+-----------------------------+
6 rows in set (0.01 sec)

查看创建表的SQL语句

show create table 表名;

mysql> show create table user;   # 末尾一定要带上逗号

image.png

删除表

drop table 表名;

mysql> drop table user;   # 末尾一定要带上逗号
Query OK, 0 rows affected (0.04 sec)

user表被删除

image.png

修改字段信息

alter table user modify user_name varchar(50) not null;   # 将user_name 从20改为50个字符

image.png

修改字段名字

alter table user change email user_email varchar(50) not null;  # 将email改成user_email

image.png

添加字段

末尾添加

alter table user add password char(30) not null comment "user_password";   # 增加password字段

image.png

指定位置添加

alter table user add password1 char(30) not null comment "user_password1" after user_name;   # 在user_name后面增加password1字段

image.png

删除字段

alter table user drop password1;        #删除字段password1

image.png

修改表名

alter table user rename to users;   # 表名改为users;to可省略

推荐 0
本文由 皮大大 创作,采用 知识共享署名-相同方式共享 3.0 中国大陆许可协议 进行许可。
转载、引用前需联系作者,并署名作者且注明文章出处。
本站文章版权归原作者及原出处所有 。内容为作者个人观点, 并不代表本站赞同其观点和对其真实性负责。本站是一个个人学习交流的平台,并不用于任何商业目的,如果有任何问题,请及时联系我们,我们将根据著作权人的要求,立即更正或者删除有关内容。本站拥有对此声明的最终解释权。

0 个评论

要回复文章请先登录注册