表“消息”的列
poster (id of user)
post_date (date of action)
表“喜欢”的列
member (id of user)
date (date of action)
表“follows”的列
follower (id of user)
follow_date (date of action)
表“achievement_log”的列
member_id (id of user)
unlock_date (date of action)
我想用这 4 个表创建一个时间线。查询应检查这些表并检索用户的 10 个最新操作。换句话说,行应该按操作日期一起排序。我怎样才能做到这一点?
最佳答案
您可以使用union all
,然后order by
和limit来完成此操作。因为您正在寻找 10 个,所以您可以限制每个组的数量:
(select 'message' as which, poster, post_date as date
from messages
where poster = @USERID
order by post_date desc
limit 10
) union all
(select 'likes', member, date
from likes
where member = @USERID
order by date desc
limit 10
) union all
(select 'follows', follower, follow_date
from follows
where follower = @USERID
order by follow_date desc
limit 10
) union all
(select 'achievement_log', member_id, unlock_date
from achievement_log
where member_id = @USERID
order by unlock_date desc
limit 10
)
order by date desc
limit 10;
此方法特别使用 union
而不是 union all
,因为 union all
效率更高。它还在子查询中进行排序和过滤,因此可以利用索引。例如,messages(poster, post_date)
上的索引将使第一个子查询更加高效。
关于mysql - 从 4 个不同的表中按日期排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24706573/