2

我有一个包含 3 列(、、、itemidaltid的mysqlcounter

我很难循环遍历每一行以counter根据重复的数量更新列itemid

我正在尝试完成的示例:

itemid | altid | counter
1        30      1
1        31      2
1        37      3
5        53      1
5        54      2
6        112     1
6        113     2
6        114     3
6        115     4

注意itemid重复的地方,counter增加+1。

该列表大约有 2500 行。我的counter专栏是空的。我对在 php 中更新的 while 循环内的增量没有运气,因为我不知道如何检测该重复值(或检查该先前值)。

这就是我现在所拥有的(不起作用):

$query = mysql_query("SELECT * FROM table") or die(mysql_error());
while ($row = mysql_fetch_assoc($query)){
$itemid = $row['itemid'];
$i=1;
    if($row['itemid']!=$itemid){
    $i=1;
    }
$id = $row['id'];
$query = mysql_query("UPDATE table SET counter='$i' WHERE id=$id") or die(mysql_error());
$i++;
}

我搜索并没有找到太多可以帮助实现这一目标的东西。非常感谢任何帮助或朝着正确的方向前进!

4

2 回答 2

6

试试这个 MySQL:

SET @pos=0, @last=0;
UPDATE `table` SET `counter`=(
    @pos:=if(
        @last=`itemid`,
        @pos+1,
        (@last:=`itemid`) and 1
    )
) ORDER BY `itemid` ASC;
于 2013-04-01T21:55:46.260 回答
0

有一个专门用于此的命令(仅在 MySQL 中):INSERT ... ON DUPLICATE KEY UPDATE

于 2013-04-01T22:22:08.907 回答