好的,所以我有一张这样的表
Col1 Col2
10 30
20 40
50 60
我正在查询数据
Query = ("SELECT * FROM TableName");
while ( $row= Mysql_fetch_array($query)) {
// code will go here
Code needs to get the prev row and the current row for every row in the table like:
This row['col1'] - prev row['col1'] = $wahatever
echo $whatever
}
我不知道如何引用php中的prev行,因为它通过while语句查看我需要说col1 - prev col1和col2 - prev col2
Anyonw能告诉我怎么做。它实际上用于解决我能做的复杂映射干扰,只是无法解决如何在循环中调用prev行数据。
任何帮助都会受到极大的欢迎
感谢你的帮助,但我不认为我正确地回答了这个问题。
我正在寻找的方法是获取每一行,然后从prev行上的col1减去col1并通过一个循环直到结束。
答案 0 :(得分:2)
您可以在SQL解决方案中完整地尝试这个
SELECT col1, col2,
col1 - @prev1,
col2 - @prev2,
@prev1 := col1, @prev2 := col2
FROM TableName, (select @prev1 := 0, @prev2 := 0) r
答案 1 :(得分:2)
$prevRow = null;
while ( $row= Mysql_fetch_array($query)) {
if($prevRow != null){
//comparison here
}
$prevRow = $row;
}
答案 2 :(得分:1)
或者,您可以将值首先存储在数组中,如
$myArr = array(); $i=0;
while ( $row= Mysql_fetch_array($query)) {
// code will go here
$myArr[$i] = $row['col1'];
$myArr[$i] = $row['col2'];
$i++;
}
然后你会知道$i-1
是db的前一行。
foreach($myArr as $i => $row) {
if( isset($myArr[$i-1]) {
$prevRow = $row;
}
// blah blah blah
}
答案 3 :(得分:1)
您可以使用mysql_data_seek 更改指向当前行的指针然后获取它,但我建议在每个步骤中存储以前的值
答案 4 :(得分:0)
如果您要比较2个不同的行,那么如果它们具有主要和自动递增的ID,它们将不会相等,但如果您只是比较行中的特定数据,那么最好的方法是存储它们,或者您可以查询所有行列但不包括id
查询当前查询的id-1,只需确保将id作为主要和自动递增,例如
<?php
$que = "SELECT * FROM table ...'";
res = mysql_query($que, $con);
if(mysql_num_rows($res)>0){
while($row = mysql_fetch_array($res)){
$counter=1;//apply this so it will not compare the first row in the data to the previous
//one because there is nothing to compare
if($counter > 1){//determine if it is the 2nd row therfore do the comparison
$currentrow=$row['id']; //this is the id of the current row which is row 2
$previousrowid=$row['id']-1; //this is the id of the row 1 which you will need to query
//the datas on it to compare it
$que2 = mysql_query("SELECT value FROM table where id= '$previousrowid' ");//query of the previous row
$r = mysql_fetch_array($que2);
$previousdata=$r['data'];
$currentdata=$row['data'];
$counter++;
if($previousdata != $currentdata)
{
echo "They Are Not Equal";
}else{
echo "They Are Equal!";
}
}//ending of the counter
}}//ending of loop
?>
希望这有帮助