SQL选择每日间隔之间的日期范围

时间:2017-09-07 12:30:28

标签: mysql sql select

我有一个数据库

database image

它每小时更新一次

我想选择 1天间隔的数据 离。

  1. 星期一
  2. 星期二
  3. 星期三
  4. ....
  5. 想要选择这些间隔之间的所有数据

    我不知道如何做到这一点

    Select * from highscores where ...........
    

    我想得到的结果:

    id player_id total economy research military date (2017-09-07 (first record of that day)
    
    id player_id total economy research military date (2017-09-08 (first record of that day)
    
    id player_id total economy research military date (2017-09-09 (first record of that day)
    
    id player_id total economy research military date (2017-09-10 (first record of that day)
    
    id player_id total economy research military date (2017-09-11 (first record of that day)
    
    .....
    

    由于

    这是解决方案:

    SELECT 
        h.id, h.player_id, h.total, h.economy, h.research, h.military, h.date
    FROM 
        highscores h
    WHERE 
        h.id = (SELECT hs.id 
                FROM highscores hs
                WHERE UNIX_TIMESTAMP(DATE_FORMAT(h.date,"%Y-%m-%d 00:00:00")) = UNIX_TIMESTAMP(DATE_FORMAT(hs.date,"%Y-%m-%d 00:00:00"))
                  AND h.player_id = hs.player_id
                ORDER BY date ASC
                LIMIT 1)
    

1 个答案:

答案 0 :(得分:0)

您可能正在寻找子查询,请勿使用select *

SELECT h.id, h.player_id, h.total, h.economy, h.reasearch, h.military, h.date
FROM highscores h
WHERE h.id = (
    SELECT hs.is FROM highscores hs
    WHERE UNIX_TIMESTAMP(DATE_FORMAT(h.date,"%Y-%m-%d 00:00:00")) = UNIX_TIMESTAMP(DATE_FORMAT(hs.date,"%Y-%m-%d 00:00:00"))
    AND h.player_id = hs.player_id
    ORDER BY date ASC
    LIMIT 1
)

使用子查询,您可以为每条记录选择一天的开头,
按日期排序,最早的第一个,所以当天的开始,并且只有当玩家匹配时 将其限制为1,因为您只需要1个匹配