我在MySQL中有一个带有“class_id”字段的表。我需要编写一个查询,它返回使用降序时间顺序排序的前15行,对于带有IN子句的列表中的每个值。
查询解释:
select * from table_x where class_id IN (1,2,3) sort by time_x desc limit 15;
在上面的示例查询中,我需要根据降序时间顺序为每个class_id(1,2和3)提取前15行。
答案 0 :(得分:3)
您需要MySQL user defined variables
SELECT
*
FROM
(
SELECT
X.*,
IF(@sameClass = class_id, @rn := @rn + 1,
IF(@sameClass := class_id, @rn := 1, @rn := 1)
) AS rank
FROM table_x AS X
CROSS JOIN (SELECT @sameClass := 0, @rn := 1 ) AS var
WHERE class_id IN (1, 2, 3)
ORDER BY class_id, time_x DESC
) AS t
WHERE t.rank <= 15
ORDER BY t.class_id, t.rank
在您的情况下,LIMIT 15
实际上将结果集限制为最多包含15条不是您想要的记录。