MySQL小结(逐渐完善)

一 、服务相关

1. 查询服务状态

sudo service mysql status

2. 启动服务

sudo service mysql start

3. 关闭服务

sudo service mysql stop

4. 重启服务

sudo service mysql restart

5. 连接服务

mysql -u 用户名 -p

二、基本命令

(一)数据库

1. 查看所有数据库

show databases;

2. 使用数据库

use 库名;

3. 查看当前所在数据库

select database();

4. 创建数据库

create database 库名 charset=utf8;

5. 删除数据库

drop database 库名;

(二)数据表

1. 查看当前数据库所有表

show tables;

2. 查看表结构

desc 表名;

3. 查看表的创建语句

show create table 表名;

4. 创建表

create table 表名;

5. 删除数据库

drop table 表名;
drop table if exists 表名;

6. 删除所有数据,保留表结构

truncate table 表名;

(三)数据

1. 插入

(1) 全部字段值

insert into 表名 values(,);

(2) 插入部分字段值

insert into 表名 (字段名,…) values(值,…),(值,…);

2. 删除

update 表名 set 字段名=值,字段名=值…… where 条件;

3. 修改

delete from 表名 where 条件;    #物理删除

4. 查询

select * from 表名;           #查询
4.1 起别名

(1) 表起别名

select 表别名.字段,… from 表名 as 别名;

(2) 字段起别名

select 字段 as 别名,… from 表名 as 别名;
4.2 排序

(1) asc:升序(默认)

select * from 表名 order by 字段名 acs, …;

(2) desc:降序

select * from 表名 order by 字段名 decs, …;
4.3 去重
select distinct 字段名 from 表名;
4.4 聚合函数

聚合函数 不能 在 where 使用

(1) count:查询总记录条数

select count(*) from 表名;

(2) max:查询最大值

select max(字段名) from 表名;  

(3) min:查询最小值

select min(字段名) from 表名;   

(4) sum:求和

select sum(字段名) from 表名;   

(5) avg:求平均数

select avg(字段名) from 表名;   
4.5 条件查询

(1) 比较运算符:<、>、>=、<=、!=、<>、=
[1] <:小于

select * from 表名 where 字段名<条件;

[2] >:大于

select * from 表名 where 字段名>条件;

[3] >=:大于等于

select * from 表名 where 字段名>=条件;

[4] <=:小于等于

select * from 表名 where 字段名<=条件;

[4] !=:不是

select * from 表名 where 字段名!=条件;

[5] <>:以外

select * from 表名 where 字段名<>条件;

[6] =:等于

select * from 表名 where 字段名=条件;

(2) 逻辑运算符:and、or、not
[1] and:与

select * from 表名 where 条件 and 条件;

[2] or:或

select * from 表名 where 条件 or 条件;

[3] not:非

select * from 表名 where not 条件;

(3) 模糊查询:like ‘%、_’
[1] %:匹配任意个字符

select * from 表名 where 字段名 like '%' ;

[2] _:匹配一个任意字符

select * from 表名 where 字段名 like '_';

(4) 范围查询:
[1] in:表示一个非连续的范围

select * from 表名 where 字段名 in(,,);

[2] between…and:表示一个连续的范围

select * from 表名 where 字段名 between … and …;

(5) 为空判断:
[1] is null:为空

select * from 表名 where 字段名 is null;

[2] is not null:不为空

select * from 表名 where 字段名 is not null;
4.6 分组查询

[1] group by:按字段名分组

select * from 表名 group by 字段名1, 字段名2;
select count(*) from 表名 group by 字段名1;

[2] having:分组筛选

select * from 表名 group by 字段名 having 条件;
4.7 分页查询

[1] start:查询的数据从第几行开始
  count:表示获取数据条数

select * from 表名 limit start, count;

[2] n:表示页数;
  m:每页显示多少记录条数

select * from 表名 limit (n-1)*m, m;  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值