2013-03-25 40 views
-2

返回我有这样一个查询:找到阵列的while循环最小值从MySQL查询

select * from posts p where p.post like '%cadillac%' ORDER BY p.upvotes DESC, 
p.unix_timestamp DESC LIMIT 20 

现在,同时通过阵列循环,我需要找到最小unix_timestamp值。例如:

$counter = 0; 
while($row = $result->fetch_assoc()){ 

// what do i do here to find the minimum timestamp value 

$counter = $counter + 1; 
} 

请指教。

+1

这听起来很简单,也许我没有得到题吧...店检查变量中的unix_timestamp值,并检查当前行的值是否较小,如果是,则将该值保存在变量中。 – Eggplant 2013-03-25 17:37:14

+0

为什么如果我可能会问这个投票呢? – coder101 2013-03-25 17:47:12

回答

2
$counter = 0; 
$min_timestamp = 0; 
while($row = $result->fetch_assoc()){ 

    //check if min hasn't been set OR if the current timestamp is less than the min 
    if(!$min_timestamp || ($row['unix_timestamp'] < $min_timestamp)) { 
     //store this timestamp as the current min 
     $min_timestamp = $row['unix_timestamp']; 
    } 

    //$counter = $counter + 1; 
} 
//once we reach here, min_timestamp will hold the minimum timestamp found 
+1

当您测试所有值为0时,这将如何返回最小值? – coder101 2013-03-25 17:52:19

+0

删除'$ min_timestamp = 0;'并添加'if(!isset($ min_timestamp))$ min_timestamp = $ row ['unix_timestamp'];'在循环内或预取第一行 – Waygood 2013-03-25 17:56:06

+0

@ coder101我不确定我理解你的问题:它将在第一次传递时进入if(),并将第一行unix_ts分配给$ min_timestamp变量。 – Alexey 2013-03-25 18:00:09

0

您可以在SQL

select MIN(unix_timestamp) from posts p where p.post like '%cadillac%' 
+0

这不是他要求的,因为它会影响回来的行数。 – 2013-03-25 17:38:37

+0

我也想要所有其他的字段值。所以可能就像'select MIN(unix_timestamp),p。* from post p where p.post like'%cadillac%'ORDER BY p.upvotes DESC, p.unix_timestamp DESC LIMIT 20'。它是否正确? – coder101 2013-03-25 17:39:01

+0

@JimmySawczuk认为这是他问的问题。 – 75inchpianist 2013-03-25 17:39:24

1

做到这一点,下面的工作:

$counter = 0; 
$min_value; 
while($row = $result->fetch_assoc()){ 
    $min_value = is_null($min_value) || $min_value > $row['unix_timestamp'] ? $row['unix_timestamp'] :$min_value ; 

    $counter = $counter + 1; 
} 
+0

这不行。 $ min_value在这里始终为空,因为您每次都要设置$ min_value = $ min_value。 ||将永远评估为真。 – 75inchpianist 2013-03-25 18:07:53

+0

翻转你的价值观的权利?它会工作 – 75inchpianist 2013-03-25 18:08:54

+0

@ 75inchpianist你是对的,也换了< for a > – 2013-03-25 18:10:52