问题
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