php - 如何从不同的特定类别中获取随机数量的最新记录并按类别排序?

标签 php mysql sql

我有一个如下所示的表格-

enter image description here

我想要类别 1 中的一条最新记录、类别 2 中的两条最新记录和类别 4 中的三条最新记录,并重复此顺序。结果如下所示

enter image description here

最佳答案

对于您建议的输出,您可以执行以下操作:

(select t.*
 from t
 where category = 'category 1'
 order by time_stamp desc
 limit 1
) union all
(select t.*
 from t
 where category = 'category 2'
 order by time_stamp desc
 limit 2
) union all
(select t.*
 from t
 where category = 'category 4'
 order by time_stamp desc
 limit 3
)
order by category, time_stamp desc;

对于 3 个已知类别,union all 可能是 MySQL 中最简单的方法。

关于php - 如何从不同的特定类别中获取随机数量的最新记录并按类别排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46993509/

相关文章:

php - yii2基础模板migrate命令使用方法

php - PDO 从表中删除指定行

mysql - SQL:处理 INSERT INTO 的列不匹配

php - 数据库中的日期是否在今天和上周之间

PHP 服务器端发布以重新创建替换安全单点登录

javascript - Google 搜索和带有关键字的网址

php - 有什么替代方法可以在不通过分析器程序的情况下分析您的 Web 应用程序?

php - 如何销毁用户名和密码的 session 以防止再次登录?

php - 使用 php/mysql 或 codeigniter 在多行中连接字符串

mysql - Mysql中不同表的两列中的两个集合的交集