我写了一个可以正常工作的查询。但是执行需要更多时间。我无法理解如何优化当前查询。
这里将有数千或数百万的数据。喜欢不喜欢每个用户每个喜欢/不喜欢插入一个新行。
我的查询:
select i.id,i.category,i.url,i.upload_by,i.upload_date,
(select count(*) from `like_dislike` where `ulike`='1' and `imageid`=i.id) AS 'allLike',
(select count(*) from `like_dislike` where `ulike`='1' and `imageid`=i.id and i.category !='4' and FROM_UNIXTIME(performdate)>= NOW() - INTERVAL '1' DAY) AS 'daytotalLike',
(select count(*) from `like_dislike` where `ulike`='1' and `imageid`=i.id and i.category !='4' and FROM_UNIXTIME(performdate)>= NOW() - INTERVAL '7' DAY) AS '7daytotalLike',
(select count(*) from `like_dislike` where `ulike`='1' and `imageid`=i.id and i.category !='4' and FROM_UNIXTIME(performdate)>= NOW() - INTERVAL '30' DAY) AS '30daytotalLike',
(select count(*) from `like_dislike` where `ulike`='1' and `imageid`=i.id and i.category !='4' and FROM_UNIXTIME(performdate)>= NOW() - INTERVAL '90' DAY) AS '90daytotalLike',
i.status from `image` as i, `like_dislike` as likeDislike
WHERE i.status='approved' and i.id=likeDislike.imageid and FROM_UNIXTIME(likeDislike.performdate)>= NOW() - INTERVAL '90' DAY
GROUP BY i.id ORDER BY '90daytotalLike' DESC Limit 50
答案 0 :(得分:0)
答案很简单:你试图在一个查询中做太多。据我所知,你想知道所有用户,哪50个用户在许多变量上得分最高。是的,对不起,有点不清楚你在这里想要实现的目标。
因此,摆脱所有子查询,并留下一个主要查询。类似的东西:
SELECT
count(*) as 90daytotalLike,
image.id,
image.category,
image.url,
image.upload_by,
image.upload_date,
image.status
FROM
image,
like_dislike
WHERE
like_dislike.ulike = 1 AND
image.category != 4 AND
image.status = 'approved' AND
image.id = like_dislike.imageid AND
FROM_UNIXTIME(like_dislike.performdate) >= NOW() - INTERVAL '90' DAY
GROUP BY image.id
ORDER BY '90daytotalLike' DESC Limit 50
如果您需要知道任何其他时期的数据,请运行单独的查询。
降低数据库负载的另一种方法是将您喜欢的总喜好存储在数据库中。它只是一个简单的计数器,没有任何花哨的东西,但是你总是可以安全地总结这些喜欢的东西。
您也可以使用期间计数器,只需在投票到期时更新每个计数器。