MySQL-显示每天的第一个和最后一个日志

时间:2018-09-24 18:58:17

标签: mysql

我有一个带有列的mysql表:id(primary),name(varchar),TIME(timestamp)

example if i have data like this 

1,name,2018-20-21 12:35:00
2,name,2018-20-21 13:38:00
3,name,2018-20-21 14:25:00
4,name,2018-20-21 15:39:00
5,name,2018-20-21 21:48:00 
6,name,2018-20-22 13:25:00
7,name,2018-20-22 14:39:00
8,name,2018-20-22 19:48:00

我想获取每天的第一笔记录和最后一笔记录

 1,name,2018-20-21 12:35:00
 5,name,2018-20-21 21:48:00 

 6,name,2018-20-22 13:25:00
 8,name,2018-20-22 19:48:00

我只想进入

all  = Radgr.includes(:nas).where("nas.realipaddr =?", "192.168.22.175")

5 个答案:

答案 0 :(得分:0)

您可以对日期的最小和最大时间组使用并集 并将其与您的表格

    select * from my_table 
    inner join  (     
    select * from (
     select   min(time) my_time 
     from my_table  
     group by date(time)
     union 
     select   max(time)
     from my_table  
     group by date(time)
    ) t on t.my_time = my_table.time
    order by  my_table.time

答案 1 :(得分:0)

尝试一下:

从表GROUP BY DATE(时间)中选择名称,MAX(时间),MIN(时间);

答案 2 :(得分:0)

希望这会有所帮助。

SELECT id, tmp.name, tmp.time FROM
(SELECT id, name, min(time) as time FROM table1 GROUP BY DATE(time)
UNION ALL
(SELECT id, name, max(time) as time FROM table1 GROUP BY DATE(time)) tmp
ORDER BY tmp.time

答案 3 :(得分:0)

您可以尝试选择每天的最小值和最大值,因为您需要整个行,因此需要加入 并过滤掉实际的最短和最长时间,需要aub查询

SELECT id, name, time
FROM
(

SELECT t2.*, MIN(DATE(t.time)) As min0 MAX(DATE(t.time)) As max0
FROM
 table t
 INNER JOIN table t2 ON t.id = t2.id
GROUP BY
 DATE (t.time), 
min0, 
max0
) a

答案 4 :(得分:0)

SELECT 
    l.id,l.name,l.time
FROM
    log l
        LEFT JOIN
    (SELECT 
        max(time) as maxTime
    FROM
        log
    GROUP BY date(time)) l1 ON l.time = l1.maxTime
        LEFT JOIN
    (SELECT 
        min(time) as minTime
    FROM
        log
    GROUP BY date(time)) l2 ON l.time = l2.minTime
WHERE
    (maxTime IS NOT NULL
        OR minTime IS NOT NUll);
SELECT * from stack.log;