Mysql在午夜之前和之后的时间

时间:2017-07-12 15:16:49

标签: mysql sql

我想让这张桌子在24小时后回到这些时间。但它什么也没有回报。

error LGHT0091: Duplicate symbol 'Error:1920' found. This typically means that an Id is duplicated. Check to make sure all your identifiers of a given type (File, Component, Feature) are unique. 

同时这完美无缺

SELECT `measurementtime`, 
       `measurementvalue` 
FROM   (SELECT `measurementtime`, 
               `measurementvalue` 
        FROM   `usermeasurements` 
        WHERE  userid = 1 
        ORDER  BY measurementtime DESC 
        LIMIT  30) AS temp1 
WHERE  Hour(measurementtime) >= '16:00:00' 
       AND Hour(measurementtime) <= '04:59:59' 
ORDER  BY Hour(measurementtime) 

所以问题似乎是我要求在两天之间找到时间。又怎样 ?我需要保留这样的时间段,而且我也不想处理日期。

条目是这样的

SELECT `measurementtime`, 
       `measurementvalue` 
FROM   (SELECT `measurementtime`, 
               `measurementvalue` 
        FROM   `usermeasurements` 
        WHERE  userid = 1 
        ORDER  BY measurementtime DESC 
        LIMIT  30) AS temp2 
WHERE  ( Hour(measurementtime) BETWEEN '05:00:00' AND '11:59:59' ) 
ORDER  BY Hour(measurementtime) 

(那些不是所有条目)

2 个答案:

答案 0 :(得分:2)

对于跨越午夜的特殊情况,请尝试:

SELECT `measurementtime`, 
       `measurementvalue` 
FROM   (SELECT `measurementtime`, 
               `measurementvalue` 
        FROM   `usermeasurements` 
        WHERE  userid = 1 
        ORDER  BY measurementtime DESC 
        LIMIT  30) AS temp1 
WHERE  HOUR(measurementtime) >= 16
       OR HOUR(measurementtime) BETWEEN 0 AND 4
ORDER  BY HOUR(measurementtime)

如果您可以在包含变量的存储过程中执行此操作,则更通用的版本可能是:

SET @range_start = 16;
SET @range_end = 4;

SELECT 
    `measurementtime`, 
    `measurementvalue` 
FROM   (SELECT `measurementtime`, 
            `measurementvalue` 
        FROM   `usermeasurements` 
        WHERE  userid = 1 
        ORDER  BY measurementtime DESC 
        LIMIT  30) AS temp1 
WHERE 
    IF(@range_start > @range_end,
        HOUR(measurementtime) >= 16
        OR HOUR(measurementtime) < 4,
        measurementtime BETWEEN @range_start AND @range_end
ORDER BY HOUR(measurementtime)

答案 1 :(得分:1)

@Sloan的答案很好,但这是使用union

的另一种选择
SELECT `measurementtime`, 
       `measurementvalue` 
FROM   (SELECT `measurementtime`, 
               `measurementvalue` 
        FROM   `usermeasurements` 
        ORDER  BY measurementtime DESC 
        LIMIT  30) AS temp1 
WHERE  Hour(measurementtime) between '16:00:00' 
       AND '23:59:59' 

union

SELECT `measurementtime`, 
       `measurementvalue` 
FROM   (SELECT `measurementtime`, 
               `measurementvalue` 
        FROM   `usermeasurements` 
        ORDER  BY measurementtime DESC 
        LIMIT  30) AS temp1 
WHERE  Hour(measurementtime) between '0:0:0' 
       AND  '04:59:59'

ORDER  BY Hour(measurementtime) 

在这里sqlfiddle尝试使用您在问题中发布的数据。 (当然,我必须删除部分用户ID才能使其正常工作。