MYSQL count標量子查詢改left join

darren__chan發表於2020-02-17
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/,如需轉載,請註明出處,否則將追究法律責任。

相關文章