表'消息'
的列poster (id of user)
post_date (date of action)
表格喜欢'
的列member (id of user)
date (date of action)
表格'的列跟随'
follower (id of user)
follow_date (date of action)
表' achievement_log'
的列member_id (id of user)
unlock_date (date of action)
我想用这4个表创建一个时间轴。查询应检查这些表并检索用户的10个最新操作。换句话说,行应按行动日期排序。我怎么能这样做?
答案 0 :(得分:2)
您使用union all
然后order by
并限制来执行此操作。因为您正在寻找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)
上的索引会使第一个子查询更有效。