获取多行并存储到变量。 Mysql和php

时间:2016-04-01 23:23:59

标签: php mysql

我正在为我的系统创建一个平均公里运行计算器。所以我想在我的数据库上运行最后两个日期和最后两个日期。

这是我目前的代码:

<?php

$conn = mysqli_connect('localhost','root','','mypms');

 $sqldates = "SELECT dateinput FROM sched ORDER BY dateinput DESC LIMIT 2";
 $sqlrun = "SELECT reading FROM sched ORDER BY reading DESC LIMIT 2"; 

 $resultdate = mysql_query($conn,$sqldates);
 $resultrun = mysql_query($conn,$sqlrun);


 while($rowdate = mysql_fetch_assoc($resultdate))
 {
     this ->
 }

 $date_difference = $date2 - $date1;

 while($rowrun = mysql_fetch_assoc($resultrun))
 {
     this ->
 }

 $run_difference = $run2 - $run1;
 $averagerun = $run_difference/$date_difference

 echo $averagerun;
?>

我应该在this上写什么,这样我就可以将$ resultrun和$ resultdate存储到$ date1,$ date2和$ run1,$ run2。

注意:dateinput的日期类型是我的mysqldatabase上的日期。

1 个答案:

答案 0 :(得分:1)

请尝试此查询 - 它将返回您的结果

SELECT 
run_difference/date_difference AS averagerun
FROM
    (
        SELECT
        DATEDIFF(date2,date1) AS date_difference,
        reading2 - reading1 AS run_difference
        FROM
        (
            SELECT 
            (SELECT dateinput FROM sched ORDER BY dateinput LIMIT 0, 1) AS date1, 
            (SELECT dateinput FROM sched ORDER BY dateinput LIMIT 1, 1) AS date2,
            (SELECT reading FROM sched ORDER BY reading DESC LIMIT 0, 1) AS reading1,
            (SELECT reading FROM sched ORDER BY reading DESC LIMIT 1, 1) AS reading2 
            FROM DUAL
        ) t1
    )t2

或“one liner”:

SELECT 
    (SELECT reading FROM sched ORDER BY reading DESC LIMIT 1, 1)-(SELECT reading FROM sched ORDER BY reading DESC LIMIT 0, 1)   /   DATEDIFF((SELECT dateinput FROM sched ORDER BY dateinput LIMIT 1, 1), (SELECT dateinput FROM sched ORDER BY dateinput LIMIT 0, 1))  AS averagerun
FROM DUAL