显示每个ID的一个结果并保持时间顺序

时间:2015-08-08 09:18:19

标签: mysql sql

我创建了以下查询,但稍有问题:

SELECT pe.*, cache.column1,p.column2,p.ID
  FROM events AS pe
  INNER JOIN cache ON pe.ID = cache.ID
  INNER JOIN places AS p ON pe.ID = p.ID
WHERE pe.createdTime > *NOW UNIX TIME*
  GROUP BY pe.ID
  ORDER BY pe.createdTime ASC LIMIT 6

它显示最新记录为例外,除非有 pe 表的多个记录 p.ID ,它显示最远的 pe 表记录(farthest = 最新的pe.createdTime 而不是即将发布的)。

尝试了一些变化,它仍然显示了这个地方最远的记录( p.ID )。寻求你的帮助!

1 个答案:

答案 0 :(得分:0)

如果我理解正确,你只需要获取最新的pe时间记录。您可以使用聚合和连接来执行此操作:

SELECT pe.*, c.column1, p.column2,p.ID
FROM events pe INNER JOIN
     cache c
     ON pe.ID = c.ID INNER JOIN
     places p ON pe.ID = p.ID INNER JOIN
     (SELECT pe.id, MIN(createdTime) as minct
      FROM events pe
      WHERE pe.createdTime > *NOW UNIX TIME*
      GROUP BY pe.id
     ) pemin
     ON pe.id = pemin.id and pe.createdTime = pemin.mminct
GROUP BY pe.ID
ORDER BY pe.createdTime ASC
LIMIT 6;

您可能不需要group by,但不知道您的数据,这很难肯定。