sql性能优化

来源:互联网 发布:高考复读知乎 编辑:程序博客网 时间:2024/06/15 11:22

1 关联表查询优化1

可能会遇到这样的工作场景,表A包含待查询的属性,但是有一些额外字段需要通过某个关联字段查询表B,这时候就需要用到join语句,如果表B很大,那么一定要在该关联字段上面建立索引。
举例来说,我有两个表:

表 内容 t_install 用户安装信息,包含user_id,from_where字段,user_id建立了索引 t_pay 用户付费信息,包含user_id,money2,money3等字段

现在要将t_pay表中的数据做分类统计,分类就依据用户的from_where字段。
我之前写的sql语句是
select C.fw, sum( C.money ) from ( select A.money as money, coalesce( B.from_where, 'TENCENT' ) as fw from ( select user_id, money2 + money3 as money from t_pay where 0 <= timestamp and timestamp < 1452128224024 and appid = '100632434' ) as A left join ( select user_id, from_where from t_install ) as B on A.user_id = B.user_id ) as C group by C.fw;
先把两个表中需要的字段分别select出来,形成临时表A和临时表B,再进行join,形成表C,可是对于表B来讲,它并没有索引,所以这个查询很慢,大概用5秒时间。
优化后的sql语句是
select A.fw, sum( A.money ) from ( select t_pay.user_id as user_id, ( t_pay.money2 + t_pay.money3 ) as money, coalesce( t_install.from_where, 'TENCENT' ) as fw from t_pay left join t_install using( user_id ) where 0 <= t_pay.timestamp and t_pay.timestamp < 1452128224024 and t_pay.appid = '100632434' ) as A group by A.fw;
这个语句在join的时候直接用了原始表(带索引的t_install),然后再进行条件过滤,这种写法用时不到10毫秒。

参考

[1] http://code.openark.org/blog/mysql/mysql-joins-on-vs-using-vs-theta-style

0 0