mysql语句学习

本文介绍了MySQL中的一些实用技巧,包括查询值为空时指定默认值、保留特定数量的小数位、修改表引擎、设置自动提交、显示表信息及查询剖析等。通过这些技巧,可以帮助开发者更好地管理和优化MySQL数据库。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一些有用的mysql语句备份:

1、mysql查询的值为空时,指定默认值

select coalesce(null,1);

 

2、从左到由保留3个字符(包括小数点)

select left(3.60962,3); -- 结果:3.6

 

 

3、修改表引擎的方法

 alter table table_name engine=InnoDB;

 

4、MySQL提供了两种事务型的存储引擎:InnoDB 和 NDB Cluster。显示是否自动提交:

show variables like'AUTOCOMMIT';

 

设置为自动提交:

SET AUTOCOMMIT = 1; -- 1或者ON表示启用,0或者OFF表示禁用。

 修改AUTOCOMMIT对非事务型的表,比如MyISAM或者内存表,不会有任何影响。

 

5、显示表的相关信息

show table status like 'tb_user'; 

 

6、剖析单条查询 使用 show profile:

set profiling = 1;
--> 在服务器上执行的所有语句,都会测量其耗费的时间和其他一些查询执行状态变更相关的数据。

 当一条查询提交给服务器时,此工具会记录剖析信息到一张临时表,并且给查询赋予一个从1开始的整数标识符。

set profiling = 1;
select * from tb_user;
show profiles;
show profile for query 2;

 停止剖析:

set profiling = 0;

 

7、在剖析后,将查询花费的时间降序:

-- 花费时间降序
set @query_id = 137;
select state,sum(duration) as total_r,
round(100*sum(duration)/(select sum(duration) from
information_schema.PROFILING where query_id = @query_id),2) as pct_r,
count(*) as calls,
sum(duration)/count(*) as "R/Call"
from information_schema.PROFILING
where query_id = @query_id
group by state
order by total_r desc;

 给@query_id赋予show profiles;查询出的Query_ID的值。

 

 

 

--------------------------------------------------------

修改数据库中的数据:

 

update tb_expert e set e.commentNum = (select count(c.id) from tb_comment c where c.toCommentUser_id = e.userid and c.parent_id is null),
e.sumScore = (select coalesce(sum(c.level),0) from tb_comment c where c.toCommentUser_id = e.userid and c.parent_id is null),
e.averageScore = (select coalesce(left(sum(c.level)/count(c.id),3),0) from tb_comment c where c.toCommentUser_id = e.userid and c.parent_id is null)
where e.commentNum != (select count(c.id) from tb_comment c where c.toCommentUser_id = e.userid and c.parent_id is null)
or e.sumScore != (select sum(c.level) from tb_comment c where c.toCommentUser_id = e.userid and c.parent_id is null)

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值