DATABASE NOTES · 01
使用 DDL 创建、查看、修改和删除数据库与数据表。
- DDL
- 表结构
MySQL 数据库与表结构管理
使用 DDL 创建、查看、修改和删除数据库与数据表。
1.库的操作
1.1新建库
#语法
# create database if not exists 库名
#eg
create database if not exists first_db;
1.2 删除库
#语法
# drop database if exists 库名
#eg
drop database if exists first_db;
1.3 查看所有库
#语法
show databases;
1.4 使用库
#语法
# use 库名;
use first_db;
2.表的操作
2.1 新建表
2.1.1字段的类型
- 整数 int
- 小数 decimal(m,d)
- 时间 datetime timestemp
- 字符 varchar(长度)
2.1.2 约束
- 主键约束 primary key
- 非空约束
- 唯一约束
2.1.3 语法
#语法
# create table if not exists 表名 (
# 字段1 类型 约束,
# 字段2 类型 约束);
#eg
create table if not exists list (
id int ,
name varchar(10) ,
catagory varchar(5) ,
price decimal(7,2) ,
date date
);
2.2 删除表
#语法
# drop table if exists 库名.表名;
#eg
drop table if exists shop_db.user;
2.3 查看所有表
#语法
show tables;
2.4 查看表里所有结构
#语法
# desc 库名.表名;
#eg
desc second_db.list;
2.5 修改表
2.5.1 增加表结构
#语法
# alter table 库名.表名 add 字段 类型 [约束];
#eg
alter table second_db.list add isvip varchar(1);
2.5.2 删除表结构
#语法
# alter table 库名.表名 drop 字段名;
#eg
alter table second_db.list drop date;
2.5.3 修改表结构
#语法
#alter table 库名.表名 change 旧字段名 新字段名 类型 [约束];
#eg
#可以只修改其中一个值,也可以全部都修改
alter table second_db.list change name Ename varchar(20);
alter table second_db.list change Ename Ename int;
2.5.4 修改表名
#语法
#rename table 库名.表名 to 库名.新表名;
#eg
rename table second_db.list to second_db. books;