Php 在将数据插入mysql数据库时为事件选择最合适的时间戳
我在mysql中有一个包含三列的下表:Php 在将数据插入mysql数据库时为事件选择最合适的时间戳,php,mysql,sql,Php,Mysql,Sql,我在mysql中有一个包含三列的下表: | event_id | event_timestamp | event_duration | 现在我想编写一部分php代码,一旦有空闲时间,并且事件适合空闲时间,它就会插入新事件 基本上,当用户决定添加某个事件时,算法会检查(在接下来的半小时内)该事件的下一个空闲时间段是什么时候,以及何时找到该时间段-使用正确的时间戳将其添加到数据库中。 每个事件都有它自己的持续时间,因此我们需要在此基础上检查时间框架 我考虑编写以下SELECT
| event_id | event_timestamp | event_duration |
现在我想编写一部分php代码,一旦有空闲时间,并且事件适合空闲时间,它就会插入新事件
基本上,当用户决定添加某个事件时,算法会检查(在接下来的半小时内)该事件的下一个空闲时间段是什么时候,以及何时找到该时间段-使用正确的时间戳将其添加到数据库中。
每个事件都有它自己的持续时间,因此我们需要在此基础上检查时间框架
我考虑编写以下SELECT查询:
select id, timestamp, duration
from table
where timestamp >= 'begin-boundary-time'
and timestamp + duration <= 'end-boundary-time'
选择id、时间戳、持续时间
从桌子上
其中时间戳>=“开始边界时间”
和时间戳+持续时间
有人知道如何帮助我解决这个问题吗?我的示例选择了所有事件(从表事件(id、开始、持续时间)中),在这些事件后面有足够的空闲时间来创建新记录并计算下一个记录和增量值。 下一个-最近的下一个事件的开始时间。 Delta-事件结束后未使用的时间(如果为空,则不受限制)
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, timestamp, duration FROM table
WHERE UNIX_TIMESTAMP(timestamp) >= NOW()
AND (UNIX_TIMESTAMP(timestamp)+duration) <= UNIX_TIMESTAMP(DATE_ADD(NOW(), INTERVAL 30 MINUTE))";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<br> id: ". $row["id"]. " - timestamp: ". $row["timestamp"]. " " . $row["duration"] . "<br>";
//here I thought about processing data and putting INSERT query
}
} else {
echo "0 results";
}
$conn->close();
?>
SELECT * FROM
(SELECT e1.id, e1.start, e1.duration, e1.start+e1.duration as end,
(SELECT min(e2.start) as next from events as e2
where e2.start > e1.start+e1.duration) as next,
(SELECT min(e3.start)-e1.start-e1.duration as delta from events as e3
where e3.start > e1.start+e1.duration) as delta
FROM events e1) t
WHERE delta >= $yourDuration OR delta is null