我有一个LIKES的MySQL表(比如ID,userID,objectID,likeDate),我希望能够计算在有问题的用户之后所做的所有'喜欢'。
通常我会得到日期:
SELECT likeDate FROM LIKES WHERE userID = <logged in user's ID>
然后查找所有日期并计算返回的行(或使用mysql COUNT),如下所示:
SELECT * FROM LIKES WHERE likeDate > <given date>
但是,我确信有一种方法可以在一个查询中执行此操作,而不是对数据库进行两次调用。有人可以帮忙吗?
由于
答案 0 :(得分:2)
将第一个查询的结果直接输入第二个查询:
SELECT COUNT(*)
FROM LIKES
WHERE likeDate > (
SELECT max(likeDate)
FROM LIKES
WHERE userID = <logged in user's ID>
)
但请注意,您需要在第一次查询中添加max()
。
此查询应该是获得答案的最快方式。为确保最佳性能,请在userID
和likeDate
上添加索引:
create index likes_userId on likes(userID);
create index likes_likeDate on likes(likeDate);
答案 1 :(得分:1)
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
或作为加入,
SELECT l1.likeDate, COUNT(1)
FROM LIKES l1
LEFT OUTER JOIN LIKES l2 ON l2.likeDate > l1.likeDate
WHERE userID = ?
GROUP BY l1.likeDate
答案 2 :(得分:0)
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>