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

标签 mysql select sql-order-by timeline

表“消息”的列

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/

相关文章:

select - 使用 Material Design Lite 进行多重选择

sql - 在 ORDER BY 子句中使用 2 个字段

mysql - 有没有一种简单的方法可以将 MySQL 数据转换为 Title Case?

php - 手动获取从主要 WordPress 网站到 WordPress 博客的链接

MySQL通过字符串加载CSV文件

php - Rails ORM 是这样工作的吗?

c# - 具有多个条件的数据表选择

css - 图形选择框

sql - 以特定方式获取订单查询

Fuel 框架中的 MySQL 按 CAST 排序