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.
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.
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.
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
. The calculation is done using a correlated subquery in the select
clause.
It will run much faster assuming you have an index on 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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.