select t.*, (select count(id) from p2p_user where create_time >=t.agent_create_time and pid = t.id ) as recommend_number, (select count(id) from p2p_user where create_time >=t.agent_create_time and pid = t.id and is_deal_load= 1 ) as recommend_load_number , (select sum(money) from p2p_deal_load where create_time >=t.agent_create_time and pid=t.id ) as deal_load_total , (select sum(income) from p2p_agent_deal_load_detail where user_id =t.id ) as agent_income from p2p_user as t;
上面是sql语句,但是需要很久才能查询出结果,怎么去优化它,求助各路大神!
你的子查询确实会很慢
改变的方法很简单,聚合函数是可以带参数的,这样就不需要子查询了
但是这样只能返回一条数据,你为啥需要select t.*我就有点搞不懂了,
还有一种很简单的就是使用join,不用子查询,这样你的查询数据就会降低很多,估计效率就上来了
select * from p2p_user as t,( select (select count(id) from p2p_user where create_time >=t.agent_create_time and pid = t.id ) as recommend_number, (select count(id) from p2p_user where create_time >=t.agent_create_time and pid = t.id and is_deal_load= 1 ) as recommend_load_number , (select sum(money) from p2p_deal_load where create_time >=t.agent_create_time and pid=t.id ) as deal_load_total , (select sum(income) from p2p_agent_deal_load_detail where user_id =t.id ) as agent_income )
多谢你的回答,后面我已经解决了,使用了 join 然后添加了索引
还有 不要 用 *
用到哪些字段就写那些字段 会好一点尽量多用多表联查 别写子查询
这个是累积求和的问题,使用join 会产生大量的中间结果集,并不一定会提高查询速度,尝试使用outer apply,应该会比子查询速度快点