MySQL查询 - 只想显示唯一条目

时间:2016-10-04 19:41:33

标签: mysql sql

我有一张这样的表

create table events 
(
    sensor_id integer not null,
    event_type integer not null,
    value integer not null,
    time timestamp unique not null
);

我想要的是显示唯一条目并获取有最长时间的条目,我已经写了这个查询

SELECT B.* 
FROM events AS B 
RIGHT JOIN (SELECT DISTINCT sensor_id, event_type, MAX(time) AS MaxDateTime 
            FROM events
            GROUP BY sensor_id, event_type
            ORDER BY MAxDateTime DESC) A ON B.time = A.MaxDateTime

我想要的是跳过时间列,只显示最终结果中的sensor_id,event_type和值,是否有任何想法?

2 个答案:

答案 0 :(得分:1)

如果你希望每sensor_id行有一行最长时间,那么就像这样:

select e.*
from events e
where e.time = (select max(e2.time)
                from events e2
                where e2.sensor_id = e.sensor_id
               );

编辑:

如果您想要每个传感器和事件的最大值,请将其包含在关联子句中:

select e.*
from events e
where e.time = (select max(e2.time)
                from events e2
                where e2.sensor_id = e.sensor_id and
                      e2.event_type = e.event_type
               );

答案 1 :(得分:1)

  • 将B. *更改为输出中的所需列...
  • 命令子查询没有'有道理所以我把它移到外面(注意你仍然可以通过一个没有显示的栏目来订购!)
  • 我添加了加入条件以包含sensor和event_Type

SELECT  B.sensor_ID, B.event_Type, B.Value
FROM events AS B 
RIGHT JOIN (SELECT distinct sensor_id, event_type, max(time) AS MaxDateTime 
            FROM events
            GROUP BY sensor_id, event_type) A 
  on B.time = A.MaxDateTime
 and B.Sensor_ID = A.Sensor_ID
 and B.Event_Type = A.Event_Type
ORDER BY B.Time