在MySQL中选择多个唯一行

时间:2010-05-20 14:34:04

标签: sql mysql select

我有一张包含以下列的表格:

ID,sysid,x,y,z,timereceived

ID是每行的唯一编号。

sysid是特定设备的ID号(大约100种不同的)

x,y和z是从设备接收的数据。 (完全随机的数字)

timereceived是收到数据的时间戳。

我需要一个SQL查询来向我显示设备a,设备b,设备c等的最后插入行。

我一直在玩很多不同的Select语句,但从来没有任何有用的东西。我设法通过使用group by获取唯一的行,但其余信息是随机的(或者至少感觉非常随机)。

有人能帮助我吗?

此表中可能有数十万条记录。

3 个答案:

答案 0 :(得分:2)

    SELECT id, sysid, x, y, z, timereceived
      FROM tbl
INNER JOIN (  SELECT sysid, max(timereceived) as "timereceived"
                FROM tbl
            GROUP BY sysid ) most_recent
     USING (sysid, timereceived)

这将为您提供完整的行,其中timereceived是最新的sysid

答案 1 :(得分:1)

SELECT sysid, MAX(timereceived) FROM yourtable GROUP BY sysid

速度不确定,因为我没有大表来测试它。确保有关sysid和timereceived的索引,这将有所帮助。实际上,对每个设备进行查询可能会更快。

答案 2 :(得分:1)

SELECT ID, sysid, x, y, z, MAX(timereceived) as max_time FROM `table` GROUP BY sysid

更新:

SELECT t1.ID, t1.sysid, t1.x, t1.y, t1.z, t1.timereceived 
    FROM `table` as t1
    JOIN (
      SELECT sysid, MAX(timereceived) as max_time
      FROM `table`
      GROUP BY sysid
    ) AS t2 ON (t2.sysid = t1.sysid AND t2.max_time = t1.timereceived)