2

我有一个 LIKES(likeID、userID、objectID、likeDate)的 MySQL 表,我希望能够计算在相关用户之后所做的所有“喜欢”。

通常我会得到日期:

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

然后找到所有日期并计算返回的行(或使用mysql COUNT),如下所示:

SELECT * FROM LIKES WHERE likeDate > <given date>

但是,我确信有一种方法可以在一个查询中执行此操作,而不是对数据库进行两次调用。任何人都可以帮忙吗?

谢谢

4

3 回答 3

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);
于 2013-02-07T12:53:29.953 回答
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
于 2013-02-07T12:52:12.847 回答
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>
于 2013-02-07T12:58:38.607 回答