实际每天每小时获得第一排

时间:2017-02-22 17:13:27

标签: mysql greatest-n-per-group

我有一张名为' pictures'具有以下内容:

picID   |   Date    |   Time    |   pic |   stationsID
1       22.02.2017  08:03:10    dadadjadadk 4
2       22.02.2017  08:13:10    ycycycycyc  4
3       22.02.2017  08:45:10    dagxhgdgwetk    4
4       22.02.2017  09:00:10    dadadjadadk 4
5       22.02.2017  09:03:10    asdasdasdyxcyw  4
6       22.02.2017  09:43:10    xvxvx       4

通过以下查询,我得到了我想要的结果 - 只获得实际一天中每小时的第一行:

select p.* from pictures p where p.Date = CURDATE() AND p.Time = (select min(p2.Time) from pictures p2 where p2.Date = p.Date and hour(p2.Time) = hour(p.Time) and p2.StationsID = 4);

1       22.02.2017  08:03:10    dadadjadadk 4
4       22.02.2017  09:00:10    dadadjadadk 4

但我的SQL查询非常慢。知道如何优化我的查询吗?

3 个答案:

答案 0 :(得分:0)

您的查询是合理的:

select p.*
from pictures p
where p.Date = CURDATE() and
      p.StationsID = 4 and  -- added this condition because it seems needed
      p.Time = (select min(p2.Time)
                from pictures p2
                where p2.Date = p.Date and hour(p2.Time) = hour(p.Time) and
                      p2.StationsID = 4
               );

对于此查询,您需要索引。我建议:pictures(Date, StationsId, Time)

答案 1 :(得分:0)

DROP TABLE IF EXISTS pictures;

CREATE TABLE pictures
(picID   INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,dt DATETIME NOT NULL
,pic VARCHAR(20) NOT NULL
,stationsID INT NOT NULL
);

INSERT INTO pictures VALUES
(1,'2017-02-22 08:03:10'  ,  'dadadjadadk',4),
(2,'2017-02-22 08:13:10'  ,  'ycycycycyc',4),
(3,'2017-02-22 08:45:10'  ,  'dagxhgdgwetk',4),
(4,'2017-02-22 09:00:10'  ,  'dadadjadadk',4),
(5,'2017-02-22 09:03:10'  ,  'asdasdasdyxcyw',4),
(6,'2017-02-22 09:43:10'  ,  'xvxvx',4);


SELECT x.* 
  FROM pictures x 
  JOIN 
     ( SELECT MIN(dt) dt 
         FROM pictures 
        GROUP 
           BY DATE_FORMAT(dt,'%Y-%m-%d %h')
     ) y 
    ON y.dt = x.dt;
+-------+---------------------+-------------+------------+
| picID | dt                  | pic         | stationsID |
+-------+---------------------+-------------+------------+
|     1 | 2017-02-22 08:03:10 | dadadjadadk |          4 |
|     4 | 2017-02-22 09:00:10 | dadadjadadk |          4 |
+-------+---------------------+-------------+------------+

答案 2 :(得分:0)

找到了一个很好的解决方案:

    SELECT p.* FROM pictures p JOIN (
SELECT MIN(Time) as Time, MIN(picID) as picID FROM pictures 
WHERE StationsID = 4 AND 
Date = CURDATE() 
GROUP BY HOUR(Time)) p1 
ON p.picID = p1.picID;