简体   繁体   English

MySQL时间戳的修改,添加和比较

[英]MySQL timestamp modification, addition, and comparison

I am creating a view that involves a little bit of fiddling with timestamps. 我正在创建一个视图,其中涉及一点时间戳。

I have a table A with timestamps. 我有一个带有时间戳的表A。 The view will process the timestamps to see if each timestamp is within a certain range (9 AM - 5 PM). 该视图将处理时间戳,以查看每个时间戳是否在一定范围内(上午9点至下午5点)。 If the timestamp is within that range, I will fetch data matching the exact time in another table (B). 如果时间戳在该范围内,我将在另一个表(B)中获取与确切时间匹配的数据。 Otherwise, I will fetch the next day (or this day's) first valid time (which is 9 AM) and the corresponding data from there. 否则,我将获取第二天(或今天)的第一个有效时间(即上午9点),并从那里获取相应的数据。

Examples: 例子:

  • A record with timestamp of 12/28/2012 17:01 -> fetch data from B for 12/29/2012 09:00 , set flag to after . 时间戳记为12/28/2012 17:01记录->从B中获取数据, 12/29/2012 09:0012/29/2012 09:00 ,将标志设置为after
  • A record with timestamp of 12/28/2012 08:59 -> fetch data from B for 12/28/2012 09:00 , set flag to before . 时间戳记为12/28/2012 08:59记录->从B中获取数据, 12/28/2012 09:0012/28/2012 09:00 ,将标志设置为before
  • A record with timestamp of 12/28/2012 09:55 -> fetch data from B for 12/28/2012 09:55 , set flag to null . 时间戳为12/28/2012 09:55记录->从B获取12/28/2012 09:55数据,并将标志设置为null

Here is what I have so far (not working, some in pseudocode). 这是我到目前为止的内容(无法正常工作,有些使用伪代码)。 I mainly don't know how to set the flag based on the comparison and then, based on flag, perform next operation on b - all in one statement. 我主要不知道如何基于比较来设置标志,然后基于标志在b上执行下一步操作-全部在一条语句中。

CREATE VIEW C as 
SELECT time, (CASE WHEN (time< '9:00' ) THEN'before'
CASE WHEN(time> '17:00') THEN'after' else null END) AS flag FROM A

//These two should be combined into one create view statement
//The below is utterly wrong, I know, but explains what I mean
SELECT(
CASE WHEN (flag=='before') THEN SELECT * FROM B WHERE B.time = time set hour='9:00'
CASE WHEN(flag=='after') THEN SELECT* FROM B WHERE B.time = time + one day set hour='9:00'
ELSE SELECT* FROM B WHERE B.time = time ) as data

Tested using this fiddle: http://sqlfiddle.com/#!2/15be5/50 使用此小提琴进行了测试: http ://sqlfiddle.com/#!2/ 15be5/50

SELECT
  q.time as original_time_check,
  q.flag as flag_check,
  case q.flag
    when 'before' then q.NINE_AM_ON_THE_DAY 
    when 'after' then q.NINE_AM_THE_NEXT_DAY 
    else q.time
  end as time


FROM
(
    SELECT
       time,
       date(time) + INTERVAL 9 HOUR as NINE_AM_ON_THE_DAY,
       date(time) + INTERVAL '1 9' DAY_HOUR as NINE_AM_THE_NEXT_DAY,  
       case
         when time < (date(time) + INTERVAL 9 HOUR) then 'before'
         when time < (date(time) + INTERVAL 17 HOUR) then 'in-range'
         else 'after'
       end as flag
    FROM 
       Your_table 
) q

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM