用于查找时差的SQL计算

时间:2013-03-26 13:21:01

标签: mysql sql time date-arithmetic

我已经使用(NOW)函数获取当前TIME并将其作为“到达时间”插入数据库。

如下所示:

$sql="INSERT INTO Time(Arrival_Time)
VALUES(NOW())";

类型是时间并且插入为;

12:17:29

我需要计算等待时间(当前时间 - 到达时间);

示例:当前时间(13:15)到达时间(12:15)

所以这会显示:

Waiting time 
1 hour 

以下是我尝试的解决方案;

<?php

$conn = mysqli_connect("localhost","root","") or die ("No connection");
mysqli_select_db($conn, "a&e") or die('Could not select database.');

$query = "SELECT Arrival_time, TIMEDIFF(Arrival_time,NOW()) as Waiting_Time FROM Time";
$result = mysqli_query($conn, $query) or die("Invalid query");

echo "<table border='1'>
<tr>
<th>Waiting Time</th>
</tr>";

while ($row = $result->fetch_object()){

 echo "<tr>
  <td>" . $row->Waiting_Time . "</td>
  </tr>";

}

echo "</table>";
mysqli_close($conn);
?>

编辑

$query = "SELECT Arrival_time, TIME_FORMAT(ABS(TIMEDIFF(CURTIME(), Arrival_time)),'%H hours') as Waiting_Time FROM Time";";

显示

Waiting time 
3 hours 

我如何使用time以便if; waiting_time超过3小时,警告“下一个必须看到这个病人!”。

2 个答案:

答案 0 :(得分:2)

您在所选字段之间的SQL语句中缺少逗号。 您正在将时间戳(字符串)与日期进行比较。您需要将字符串转换回来。

更改此

SELECT Arrival_time TIMEDIFF(Arrival_time,NOW()) as Waiting_Time FROM Time

SELECT Arrival_time, TIMEDIFF(DATETIME(Arrival_time),NOW()) as Waiting_Time FROM Time

答案 1 :(得分:1)

您可以尝试使用CURRENT_TIMECURTIME()代替NOW()

SELECT Arrival_time, TIMEDIFF(Arrival_time,CURRENT_TIME) as Waiting_Time FROM Time;

[编辑]
由于NOW() DATETIME ,因此不仅仅是时间。 MySQL Doc

[ADD]
您可以使用TIME_FORMAT(time_diff, '%H hours')来获取时间 要删除-,请添加ABS()方法以获取绝对值:

SELECT Arrival_time, TIME_FORMAT(ABS(TIMEDIFF(Arrival_time,CURRENT_TIME)),'%H hours') as Waiting_Time FROM Time;

[如果timediff&gt;更改返回值; 3]

SELECT Arrival_time, TIME_FORMAT(ABS(TIMEDIFF(Arrival_time,CURRENT_TIME)),'%H hours left') as Waiting_Time FROM Time WHERE CAST(TIME_FORMAT(ABS(TIMEDIFF(Arrival_time,CURRENT_TIME)),'%H') as UNSIGNED INTEGER)>3

您可以使用timediff值进行所有操作...此处,查询只返回差异大于3小时的行...