MySQL学习
DDL
数据库操作
net start mysql80 #启动mysql
net stop mysql80 #停止mysql
mysql -u root -p #进入mysql
- if not exists 如果不存在则创建,如果存在则不执行操作,并且不报错
- if exists 如果存在则执行操作,不存在则不执行操作,并且不报错
show databases; #查询数据库
select database(); #查询当前数据库
create database [if not exists] 数据库名 [default charset 字符集] [collate 排序规则]; #创建数据库
drop database [if exists] 数据库名; #删除数据库
use 数据库名; #使用数据库
表操作
查询
show tables; #查询当前数据库所有表
desc 表名; #查询表结构
show create table 表名; #查询指定表的建表语句
创建
creat table 表名
(
字段1 字段类型 [comment 注释],
字段2 字段类型 [comment 注释],
字段3 字段类型 [comment 注释],
字段4 字段类型 [comment 注释],
......
)[comment 注释];
以一个4×4表格为例:
id | 姓名 | 年龄 | 性别 |
---|---|---|---|
1 | … | ||
2 | … | ||
3 | … |
修改&删除
alter table 表名 add 字段名 字段类型 [comment 注释][约束]; #添加字段
alter table 表名 modify 字段名 新数据类型(长度); #修改数据类型
alter 表名 change 旧字段名 新字段名 类型(长度) [comment 注释][约束]; #修改字段名和字段类型
alter table 表名 drop 字段名; #删除字段
alter table 表名 rename to 新表名; #修改表名
drop table [if exists] 表名; #删除表
truncate table 表名; #删除指定表,并重新创建该表
数据类型
- 无符号 在数据类型后添加“unsigned”,如 “id int unsigned”
- 精度 指数据小数点前的位数
- 标度 指数据小数点后的位数
- 定长 指定一固定大小空间存储数据,如char(10)其所占空间均为10,数据小于10则使用空格补齐,大于则报错,性能较强
- 变长 数据所占空间大小随数据大小变化,性能较弱
总结
DDL中常用语句:
net start mysql80 #启动mysql
net stop mysql80 #停止mysql
mysql -u root -p #进入mysql
show databases; #查询数据库
select database(); #查询当前数据库
create database [if not exists] 数据库名 [default charset 字符集] [collate 排序规则]; #创建数据库
drop database [if exists] 数据库名; #删除数据库
use 数据库名; #使用数据库
show tables; #查询当前数据库所有表
desc 表名; #查询表结构
show create table 表名; #查询指定表的建表语句
creat table 表名
(
字段1 字段类型 [comment 注释],
字段2 字段类型 [comment 注释],
字段3 字段类型 [comment 注释],
字段4 字段类型 [comment 注释],
......
)[comment 注释];
alter table 表名 add 字段名 字段类型 [comment 注释][约束]; #添加字段
alter table 表名 modify 字段名 新数据类型(长度); #修改数据类型
alter 表名 change 旧字段名 新字段名 类型(长度) [comment 注释][约束]; #修改字段名和字段类型
alter table 表名 drop 字段名; #删除字段
alter table 表名 rename to 新表名; #修改表名
drop table [if exists] 表名; #删除表
truncate table 表名; #删除指定表,并重新创建该表