按日期从4个不同的表中排序

时间:2014-07-11 21:07:54

标签: mysql select sql-order-by timeline

表'消息'

的列
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个最新操作。换句话说,行应按行动日期排序。我怎么能这样做?

1 个答案:

答案 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)上的索引会使第一个子查询更有效。