简体   繁体   English

进一步提高SQL查询的效率

[英]Further Improving Efficieny of SQL Query

Having got an excellent answer to my last question: Improving Efficiency of my SQL (thanks @Bohemian) I have now realised I was a little short-sighted as there is an added complication. 对于我的最后一个问题,我得到了一个很好的答案: 提高SQL的效率 (感谢@Bohemian)我现在意识到自己有点短视,因为它增加了复杂性。

Using the same table LIKES (likeID,userID,objectID,likeDate) the idea is that a person earns 1 point each time someone likes an object after they have liked it. 使用相同的表LIKES(likeID,userID,objectID,likeDate),想法是一个人每次喜欢一个对象后,每次获得1分。

With the help from the previous question I can get the number of likes after a users like but now I need to consider that there are objects in this problem. 在上一个问题的帮助下,我可以得到用户喜欢后的点赞次数,但现在我需要考虑这个问题中是否存在对象。

I want to be able to calculate the number of points a user is entitled to by counting the likes made after theirs for each object they liked (oooh that was a messy sentence). 我希望能够通过计算用户喜欢的每个对象之后获得的点赞来计算用户有权获得的积分数(哦,那是一个凌乱的句子)。

I am considering a further "nesting" of SQL but this is out of my league and so I can't really offer any code other than what's in the last question. 我正在考虑对SQL进行进一步的“嵌套”,但这超出了我的能力,因此除了上一个问题中的内容之外,我无法提供其他任何代码。

You can do this with a correlated subquery: 您可以使用相关子查询来执行此操作:

select l.userid, l.objectid, l.LikeDate,
       (select count(*) from likes l2 where l2.objectid = l.objectid and l2.LikeDate >= l.likeDate and l2.userid <> l.userid
       ) as NumLikesAfterward
from likes l

What this is doing is counting the number of likes on an object, by other users, after a given like. 这是在计算给定的点赞后,其他用户对某个对象点赞的次数。 It returns one row for every row in likes . 它返回在每一行一行likes The calculation is done using a correlated subquery in the select clause. 使用select子句中的相关子查询来完成计算。

It will run much faster assuming you have an index on likes(objectid, likedate, userid) . 假设您在likes(objectid, likedate, userid)上有一个索引,它将运行得更快。

To get the total points for a user: 要获取用户的总积分:

select sum(NumLikesAfterward) as TotalPoints
from (select l.userid, l.objectid, l.LikeDate,
             (select count(*) from likes l2 where l2.objectid = l.objectid and l2.LikeDate >= l.likeDate and l2.userid <> l.userid
             ) as NumLikesAfterward
      from likes l
      where userid = $userid
     ) uol

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM