ITPub博客

首页 > 数据库 > MySQL > MYSQL count标量子查询改left join

MYSQL count标量子查询改left join

原创 MySQL 作者:darren__chan 时间:2020-02-17 17:53:09 0 删除 编辑
SELECT
homepageId,
userId,
homepagesummary,
totalviews,
totalleadpercents,
totalappointments,
homepagestatus,
linkphone,
imagepath,
createtime,
updatetime,
recommendtime,
sortcode,
designerimagepath,
isrecommend,
(
SELECT
count(*)
FROM
homepagexxxrelation
WHERE
homepageid = h.homepageid
AND groundingstatus = 0
) AS totalxxx,
(
SELECT
count(*)
FROM
homepagexxxrelation
WHERE
homepageid = h.homepageid
AND groundingstatus = 0
AND Createtime >= DATE_SUB(sysdate(), INTERVAL 7 DAY)
) AS weektotalxxx
FROM
designerhomepage h
WHERE
1 = 1  and isrecommend=1 order by  weektotalxxx DESC,
homepageid DESC;
优化后:
SELECT
h.homepageId,
h.userId,
h.homepagesummary,
h.totalviews,
h.totalleadpercents,
h.totalappointments,
h.homepagestatus,
h.linkphone,
h.imagepath,
h.createtime,
h.updatetime,
h.recommendtime,
h.sortcode,
h.designerimagepath,
h.isrecommend, 
  ifnull(h2.cnt2,0)  AS totalscheme,
ifnull(h2.cnt1,0) AS weektotalxxx
FROM
designerhomepage h
LEFT JOIN (
SELECT
Homepageid,
sum(case when  HP.Createtime >= DATE_SUB(sysdate(), INTERVAL 7 DAY) then 1 else 0 end) cnt1,
count(*) cnt2
FROM
homepagexxxrelation hp
WHERE
HP.groundingstatus = 0
GROUP BY
Homepageid
) h2 ON h2.homepageid = h.homepageid
WHERE
1 = 1
and isrecommend=1
ORDER BY
weektotalxxx DESC,
homepageid DESC;


来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/29863023/viewspace-2675930/,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
永远只是个追逐者 wx: darren_chan

注册时间:2014-09-09

  • 博文量
    159
  • 访问量
    1043982