mysql数据库如何优化?

30种SQL查询语句优化方法:

1、应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:

select id from t where num is null
可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:

select id from t where num=0
2、尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:

select id from t where num=10 or num=20
可以这样查询:

select id from t where num=10
union all
select id from t where num=20
3、下面的查询也将导致全表扫描:(不能前置百分号)

select id from t where name like ‘�c%’
若要提高效率,可以考虑全文检索。

4、in 和 not in 也要慎用,否则会导致全表扫描,如:

select id from t where num in(1,2,3)
对于连续的数值,能用 between 就不要用 in 了:

select id from t where num between 1 and 3
5、如果在 where 子句中使用参数,也会导致全表扫描。因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择。然 而,如果在编译时建立访问计划,变量的值还是未知的,因而无法作为索引选择的输入项。如下面语句将进行全表扫描:

select id from t where num=@num
可以改为强制查询使用索引:

select id from t with(index(索引名)) where num=@num

8、很多时候用 exists 代替 in 是一个好的选择:

select num from a where num in(select num from b)
用下面的语句替换:

select num from a where exists(select 1 from b where num=a.num)

9、尽可能的使用 varchar/nvarchar 代替 char/nchar ,因为首先变长字段存储空间小,可以节省存储空间。

10、任何地方都不要使用 select * from t ,用具体的字段列表代替“*”。

11.尽量添加限制条件,减少检索数据的行数

12.能够分开查询的,尽量分开,可以提高每次响应的速度

13.尽量使用索引列为查询的首列

14.尽量使用链接查询替代子查询

15.尽量不要修改主键的值

16.如果字段的值的约束写错会导致索引不生效而全表扫描,字段类型尽量别写错。

17、分页:查询数据量比较大的时候可以考虑分页,降低压力。

二、.性能优化
1.分库,
主从备份 读写分离
2.分表
一张表中的字段最好不要超过15个,将一张表拆分成 两张或者多张表
允许部分字段冗余

        user
            id name gennder phone emai info 

        拆分:
            user
                id name phone
            info
                gennder phone emai info
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值