我在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行
你需要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条记录,这不是您想要的。