Improving Efficiency of my SQL

2019-07-18 05:40发布

I have a MySQL table of LIKES (likeID,userID,objectID,likeDate) and I would like to be able to count all the 'likes' that have been made after the user in question.

Typically I would get the date:

SELECT likeDate FROM LIKES WHERE userID = <logged in user's ID>

and then find all dates and count the row returned (or use mysql COUNT) like this:

SELECT * FROM LIKES WHERE likeDate > <given date>

However, I'm sure there is a way to do this in one query rather than making two calls to the database. Can anyone help?

Thanks

3条回答
来,给爷笑一个
2楼-- · 2019-07-18 06:05
SELECT * FROM LIKES WHERE likeDate > 
IFNULL((SELECT max(likeDate) FROM LIKES WHERE userID = <logged in user's ID> 
                                  adn  objectId=<question's Id>),0)
and objectId=<question's Id>
查看更多
beautiful°
3楼-- · 2019-07-18 06:09
SELECT l1.likeDate, 
    (SELECT COUNT(1) FROM LIKES l2 WHERE l2.likeDate > l1.likeDate) AS likesAfter
FROM LIKES l1
WHERE userID = ?
GROUP BY l1.likeDate

Or as a join,

SELECT l1.likeDate, COUNT(1)
FROM LIKES l1
LEFT OUTER JOIN LIKES l2 ON l2.likeDate > l1.likeDate
WHERE userID = ?
GROUP BY l1.likeDate
查看更多
爷、活的狠高调
4楼-- · 2019-07-18 06:18

Feed the result of the first query directly into the second one:

SELECT COUNT(*)
FROM LIKES
WHERE likeDate > (
    SELECT max(likeDate)
    FROM LIKES
    WHERE userID = <logged in user's ID>
)

However note that you need to add the use of max() in your first query.

This query should be the fastest possible way to get your answer. To ensure maximum performance, add indexes on both userID and likeDate:

create index likes_userId on likes(userID);
create index likes_likeDate on likes(likeDate);
查看更多
登录 后发表回答