MySQL常用命令

登录:

1
2
3
4
mysql -u root -p
或者
mysql -u root -p12345
--没有空格不然会吧空格识别为密码

启动&停止数据库服务

注:在管理员运行cmd否则不能启动

1
2
3
net start mysql %启动服务%

net stop mysql %停止服务%

数据库的基本操作

修改密码:

1
2
updata mysql.user set authentication_string=password('密码') where user='root' and host = 'localhost';--修改密码
flush privileges; --刷新权限

创建数据库

1
create database [if not exists] 库名;

查看数据库

1
2
查看库:
show databases;

选择数据库

1
use 库名;

删除数据库

1
drop database [if exists] 数据库名

数据表的基本操作

创建表

1
2
3
4
5
6
7
create table 表名 
(
字段1 数据类型 [列级约束条件] [默认值],
字段2 数据类型 [列级约束条件] [默认值],
...
[表级约束条件]
);

修改表名

1
alter table 原表名 rename [to] 新表名; ---to为可选参数不影响结果

删除数据表

1
drop table 表名

显示所有表

1
show tables;

显示表详细结构

1
show create table 表名;

查看表基本结构信息

1
describe 表名 或 desc 表名

添加字段

1
alter table 表名 add 新字段名 数据类型 [约束条件] [first | after 已存在字段名];

添加字段描述

1
alter table 表名 modify 字段名 数据类型 comment 描述;

修改字段名

1
alter table 表名 change 原字段名 新字段名 新数据类型;

修改字段数据类型

1
alter table 表名 modify 字段名 数据类型;

删除字段

1
alter table 表名 drop 字段名

修改字段排序位置

1
alter table 表名 modify 字段名1 数据类型 first | after 字段2;

数据完整性约束

主键约束

1
2
3
4
5
6
1、在定义字段(列)的同时指定主键。
字段名 数据类型 primary key [默认值];
2、在定义所有列之后指定主键
[constraint 约束名] primary key(字段名);
3、多字段联合主键
primary key(字段1 字段2 字段3 ...);

唯一约束

1
2
3
4
1、在定义完一个字段之后直接指定唯一约束。
字段名 数据类型 unique
2、在定义完所有字段之后指定唯一约束
[constraint 约束名] unique(字段名)

非空约束

1
字段名 数据类型 not null;

默认约束

1
字段名 数据类型 default 默认值;

字段自动增加

1
字段名 数据类型 auto_increment;

外键约束

1
[constraint 外键名] foreign key(字段1 [,字段2, ...]) references 主表名(主键列1 [,主键列2, ...]);

表数据的基本操作

添加数据

1
2
3
4
insert [low_priority | delayed | high priority] [ignore] 
[into] 表名 [(字段名,...)]
values({值,default},...),(...), ...
[no duplicate key update 字段名=表达式, ...];

修改数据

1
update [low_priority] [ignore] 表名 set 字段1 =1 [,字段2 =2 ...] [where 条件表达式] [order By...] [limit 行数];

删除数据

1
2
delete [low_priority] [quick] [ignore] from 数据表名 [where 条件表达式] [order by...] [limit 行数];
truncate [table] 数据表; --删除所有行

数据查询

基本查询语句

1
2
3
4
5
6
7
8
select [distinct] <字段列表> 
from <数据表>
[<连接类型> join <数据表> on <连接条件>]
[where <查询条件>]
[group by <字段列表>]
[having <条件表达式>]
[order by <字段列表>]
[limit [<coffset,><限制行数>]]

所有字段数据查询

1
select * from <表名>;

指定字段数据查询

1
select <字段1> [,字段2,...] from <表名>;

去出重复数据查询-distinct

1
select distinct <字段名> from <表名>;

限制结果行数查询

1
2
3
4
select * | 字段列表
from 数据表名
limit [位置偏移量,] 行数;
# SELECT * FROM table LIMIT 1;

条件数据查询

1
2
3
4
5
6
7
8
9
SELECT 字段列表
FROM <表名>
WHERE 查询条件表达式;
# 条件表达式
# 关系运算符 ( < , > , = , != , >= , <=)
# 逻辑运算符 ( AND(&&) , OR(||) , XOR , NOT(!) )
# 关键字BETWEEN AND 范围查询
# 关键字LIKE模糊查询
# 关键字IS NULL空值查询