在上篇札记MySQL札记5_语句分类(面试考点)归纳了4种常见的MySQL
语句。在本篇札记中,主要介绍的是:数据定义语言DDL,data defination language
。
常用操作
在操作数据表table
之前,首先要选择进入某个数据库database:database---table
先进入mysql
中
image.png
查看所有的数据库,选择peter
数据库进入
image.png
创建数据表结构
create table 表名(
列名 列类型 关键词,
......
列名 列类型
);
末尾一定要带上逗号
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;
image.png
修改表名
alter table user rename to users;