简体   繁体   中英

Get Data between 15 and 30 Minutes ago

I have data that constantly fills up a MySQL database. The past full quarter hour of data needs to be checked when a PHP script runs. Tried using MySQL with something like SEC_TO_TIME(FLOOR((TIME_TO_SEC(UTC_TIME())-450)DIV 900)*900) however since this does not know when a new hour is started it breaks when ran between 0-15 minutes.

+---------------------+------------+
|    date             |    data    |
+---------------------+------------+
| 2016-12-10 17:35:03 | infos      |
| 2016-12-10 17:55:03 | info0      |
| 2016-12-10 18:00:01 | info1      |
| 2016-12-10 18:04:00 | info2      |
| 2016-12-10 18:13:10 | info3      |
| 2016-12-10 18:16:30 | info4      |
+---------------------+------------+

What I'm trying to accomplish based on the above if the query is ran at 18:17, it gets these rows since the last full quarter hour was between 18:00 and 18:15:

| 2016-12-10 18:00:01 | info1      |
| 2016-12-10 18:04:00 | info2      |
| 2016-12-10 18:13:10 | info3      |

If the query is ran at 18:05, gets only this row because the last full quarter hour was between 17:45 and 18:00:

| 2016-12-10 17:55:03 | info0      |

I believe you can use the GROUP BY in SQL to achieve what you're doing. However, I attatched a PHP code method you could wrap in an Object or method to achieve the same thing.

 # your driver and credentials
$obj = new PDO();  

 # your sql query
$stmp = ( $obj->Prepare( 'SELECT * from table' )
    ->execute( );

 # loop through the results
foreach( $stmp->fetchAll( ) as $row )
{
     # work out the difference between the entry timestamp and script execute timestamp
    $time = strtotime( gmdate( "H:i:s", strtotime( $row[ 'column' ] ) ) ) - time( );

     # compare database entry to pre-set entry
    if( time( ) >= gmdate( "H:i:s", 900 ) )
    {
         # 15 minutes has passed
        echo $row[ 'column' ];
    }
}

Hope this helped.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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