Improving Efficiency of my SQL

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-12 17:27:32

问题


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


回答1:


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);



回答2:


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



回答3:


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>


来源:https://stackoverflow.com/questions/14751541/improving-efficiency-of-my-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!