timediff在mysql中没有使用date_format

时间:2012-11-19 15:59:26

标签: php mysql time mysqli

我创建了一个查询,使用total_time1计算来自time_intime_out的其他两个字段的timediff(time_out, time_in) AS total_time1

现在,我希望将该时间转换为更好的格式,而不是通常的hh:mm:ss,因此在同一查询中我做了DATE_FORMAT(total_time1, '%l:%i') AS total_time2,但由于某种原因,每当我输入一个时它都不起作用新的进出时间。

这是查询:

$sql="SELECT 
        DATE_FORMAT(time_in, '%l:%i %p') AS time_in,
        DATE_FORMAT(time_out, '%l:%i %p') AS time_out,
        timediff(time_out, time_in) AS total_time1,
        DATE_FORMAT(total_time1, '%l:%i') AS total_time2,
      FROM $table";

$result = $mysqli->query($sql);

while($row = $result->fetch_array()){
    <td><?php echo $row['time_in']; ?></td>
    <td><?php echo $row['time_out']; ?></td>
    <td><?php echo $row['total_time1']; ?></td>
    <td><?php echo $row['total_time2']; ?></td>
}

我在其自己的页面上的大表上显示所有内容(包括time in,out,totaltime1和totaltime2)。 total_time1就像我说的那样,但total_time2没有显示任何内容。没有错误或任何东西。我在这做错了什么。

2 个答案:

答案 0 :(得分:3)

您不能使用在同一查询中创建的别名

你必须像这样再次写它

$sql="SELECT 
        DATE_FORMAT(time_in, '%l:%i %p') AS time_in,
        DATE_FORMAT(time_out, '%l:%i %p') AS time_out,
        timediff(time_out, time_in) AS total_time1,
        DATE_FORMAT(timediff(time_out, time_in), '%l:%i') AS total_time2
      FROM $table";

另外,如果你想格式化时间,

您不应使用DATE_FORMAT,而应使用TIME_FORMAT

像这样

$sql="SELECT 
            TIME_FORMAT(time_in, '%l:%i %p') AS time_in,
            TIME_FORMAT(time_out, '%l:%i %p') AS time_out,
            timediff(time_out, time_in) AS total_time1,
            TIME_FORMAT(timediff(time_out, time_in), '%l:%i') AS total_time2
          FROM $table";

Here's关于MySQL中所有日期和时间函数的文档

答案 1 :(得分:0)

您无法自行引用该列。你还有一个额外的逗号,我认为这是一个错字。

你需要这样的东西:

$sql="SELECT time_in, time_out, total_time1, DATE_FORMAT(total_time1, '%l:%i') AS total_time2
FROM (SELECT 
        DATE_FORMAT(time_in, '%l:%i %p') AS time_in,
        DATE_FORMAT(time_out, '%l:%i %p') AS time_out,
        timediff(time_out, time_in) AS total_time1
      FROM $table) a";