帮忙优化一个mysql的语句,很多重复子查询

selectdistinct(selectsum(value1)assum1fromtable1whererecdate=(selectmax(recdate)asmax... select distinct (select sum(value1) as sum1 from table1 where recdate=(select max(recdate) as max from table1)) as sum1,(select sum(value2) as sum2 from table1 where recdate=(select max(recdate) as max from table1)) as sum2,recdatefrom table1 where recdate = (select max(recdate) as max from table1)

说明 (select max(recdate) as max from table1)这个子查询用到3次,而且所有查询都是在一张表里
展开
 我来答
爱可生云数据库
2020-11-13 · MySQL开源数据库领先者
爱可生云数据库
爱可生,金融级开源数据库和数据云服务整体解决方案提供商;优秀的开源数据库技术,企业级数据处理技术整体解决方案提供商;私有云数据库云服务市场整体解决方案提供商。
向TA提问
展开全部

子查询优化策略

对于不同类型的子查询,优化器会选择不同的策略。

1. 对于 IN、=ANY 子查询,优化器有如下策略选择:

  • semijoin

  • Materialization

  • exists

  • 2. 对于 NOT IN、<>ALL 子查询,优化器有如下策略选择:

  • Materialization

  • exists

  • 3. 对于 derived 派生表,优化器有如下策略选择:

  • derived_merge,将派生表合并到外部查询中(5.7 引入 );

  • 将派生表物化为内部临时表,再用于外部查询。

  • 注意:update 和 delete 语句中子查询不能使用 semijoin、materialization 优化策略

已赞过 已踩过<
你对这个回答的评价是?
评论 收起
hch686
2011-05-10 · 超过64用户采纳过TA的回答
知道小有建树答主
回答量:248
采纳率:0%
帮助的人:135万
展开全部
看代码看的晕,给你个建议吧,就不仔细看你的东西了
一个是做临时表,分别几个不同的条件放到几个临时表,然后最后一个语句进行总结处理

另外一个就是,拆分,比如说一个表table
你可以
select * from table a,table b
where a.recdate=b.recdate
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
dl_会飞的青蛙
2011-05-10 · TA获得超过2457个赞
知道大有可为答主
回答量:3294
采纳率:0%
帮助的人:3439万
展开全部
select sum(value1) as sum1,sum(value2) as sum2,recdate
from table1
where recdate = (select max(recdate) as max from table1)
group by recdate
追问
select distinct (select sum(value) as sum1 from table1 where type='system' and recdate=(select max(recdate) as max from table1)) as sum1,(select sum(value) as sum2 from table1 where type='user' and recdate=(select max(recdate) as max from table1)) as sum2,recdatefrom table1 where recdate = (select max(recdate) as max from table1)

那这个可以优化吗?value1和value2通过type来区分,能优化再加分
追答
可以的!~
select sum(case when type='system' then value1 else 0 end) as sum1,sum(case when type='user' then value2 else 0 end) as sum2,recdate
from table1
where recdate = (select max(recdate) as max from table1)
group by recdate
本回答被提问者采纳
已赞过 已踩过<
你对这个回答的评价是?
评论 收起
收起 更多回答(1)
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式