我有一个表格来跟踪每个用户与每个帖子相关的事件:
CREATE TABLE users2posts (
uts int unsigned not null comment 'uts for Unix Time Stamp',
user_id int unsigned not null,
post_id int unsigned not null,
action set('follow','unfollow','upvote','downvote'),
PRIMARY KEY (uts,user_id,post_id)
);
我想获取当前关注给定帖子的所有用户的 ID。这意味着获取最后一次“关注”或“取消关注”操作为“关注”的所有用户的 ID。我想出的是这样的:
SELECT user_id, action
FROM users2posts
WHERE post_id=1
AND (action="follow" OR action="unfollow")
GROUP BY user_id
ORDER BY uts DESC;
然后我循环遍历所有结果并存储最后一个操作是关注该帖子的用户的 id:
foreach ($ROWS as $ROW)
if ($ROW['action'] == 'follow')
$FOLLOWERS[] = $ROW['user_id'];
但是,这不起作用。它存储最后一个操作是取消关注帖子的用户的 ID。我哪里错了?提前致谢。
更新
我认为问题出在MySQL查询上。其背后的想法是选择所有关注或取消关注该帖子的用户,然后按日期对它们进行排序,并使用 GROUP BY 子句将选择范围缩小到每个用户执行的最后一个操作。但是,查询似乎是在排序之前进行分组的。这是应该发生的事情吗?我该如何解决它?
最佳答案
select *
from users2posts
where uts in
(
select max(uts) as lastaction
from users2posts
where post_id=1
group by user_id
)
and action = 'follow'
子选择将获取每个用户对帖子 1 的最后一个操作(如果有),而主查询仅获取那些实际follow
的操作。
关于php - 如何获取所有关注帖子的用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9351057/