1

I've made a query that calculates the total_time1 from 2 other fields called time_in and time_out using timediff(time_out, time_in) AS total_time1.

Now, I want to convert that time into a better format instead of the usual hh:mm:ss so in the same query I did DATE_FORMAT(total_time1, '%l:%i') AS total_time2, but for some reason it doesn't work whenever I input a new time in and out.

This is the query:

$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>
}

I'm displaying everything (including time in, out, totaltime1 and totaltime2) on a large table on it's own page. total_time1 works like I said, but total_time2 displays nothing. No errors or anything. What am I doing wrong here.

4

2 回答 2

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";

这是有关 MySQL 中所有日期和时间函数的文档

于 2012-11-19T16:01:00.323 回答
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";
于 2012-11-19T16:02:16.187 回答