我在 mysql 中有下表,其中包含三列:
| 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'
然后迭代 php 代码中的选定结果,直到找到一个空闲插槽 - 当我找到一个空闲插槽时,我只会在那里执行 INSERT 查询,但这就是我卡住的部分。到目前为止我编写的基本代码如下所示:
<?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();
?>
有人知道如何帮助我解决这个问题吗?
最佳答案
我的示例选择所有事件(从表事件(id、开始、持续时间)),后面有足够的空闲时间用于新记录并计算 Next 和 Delta 值。 下一个 - 最近的下一个事件的开始时间。 Delta - 事件结束后未使用的时间(如果为空则无限制)
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
关于php - 将数据插入mysql数据库时为事件选择最合适的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29510753/