通过向这些行添加1来更新第2行之后的所有行

时间:2012-04-10 19:32:58

标签: php mysql

我有一张这样的表:

id  subject        position         visible

1   Home               1               1
2   About us           2               1
3   Our partners       3               1
18  Products           4               1
19  Extra              5               0

我想在position = 2之后的所有行中添加数字1,如下所示:

id  subject        position         visible

1   Home               1               1
2   About us           2               1
3   Our partners       4               1
18  Products           5               1
19  Extra              6               0

我试过这样,但这不起作用:

$row=mysql_query("SELECT * FROM table");
$count=mysql_num_rows($row);
$position=3;
$add=($position+1);
while($position<=$count)
{
    $sql="UPDATE subjects SET position=$add WHERE position=$position";
    mysql_query($sql);
    $add++;
    $position++;
}

应用上面的代码后,我的表格如下:

id  subject        position         visible

1   Home               1               1
2   About us           2               1
3   Our partners       6               1
18  Products           6               1
19  Extra              6               0

有没有解决方案?

3 个答案:

答案 0 :(得分:11)

为什么不呢:

UPDATE subjects SET position=position+1 WHERE position>2

答案 1 :(得分:3)

UPDATE subjects SET position=position + 1 WHERE position >= 3

答案 2 :(得分:1)

 update subjects set position = position +1 where position >2