使用基于字段重置的递增值更新字段

时间:2014-04-25 15:03:53

标签: mysql

我在MySQL中有以下表格:

|id|user|line|
|10|0001|    |
|11|0001|    |
|12|0002|    |
|13|0003|    |
|14|0003|    |
|15|0003|    |

我需要将行列更新为一个递增的数字,为每个用户重置,所以我最终得到这个:

|id|user|line|
|10|0001|   1|
|11|0001|   2|
|12|0002|   1|
|13|0003|   1|
|14|0003|   2|
|15|0003|   3|

我过去曾在MS SQL中使用ROW_NUMBER() OVER (PARTITION...。有没有办法在MySQL中做到这一点?

2 个答案:

答案 0 :(得分:1)

我不知道如何使用纯SQL执行此操作。 您可以查看MySQLs GROUP BY函数,看看是否可以将您带到任何地方?


这是一个PHP解决方案:

<?php
$mysql_host="localhost";
$mysql_user="MYSQL USERNAME";
$mysql_password="MYSQL PASSWORD";
$mysql_database_name="SOME_DB_NAME";
$table="MYSQL TABLE NAME";

$con=mysql_connect($mysql_host, $mysql_user, $mysql_password);
mysql_selectdb($mysql_database_name, $con);
$query=mysql_query("SELECT * FROM `$table`");

// $toUpdate will be used to store the info that is needed to update
// the appropriate line with the respective line number

// $userTracker will contain which "line" number we are on
while(mysql_fetch_assoc($query) as $row){
    $rowID=$row['id'];
    $userNumber=$row['user'];
    $nextLineNumberForThisUser=$userTracker[$userNumber];
    if (!$nextLineNumberForThisUser){
        $nextLineNumberForThisUser=1;
    }
    else{
        ++$nextLineNumberForThisUser;
    }

    $u=&$toUpdate[];
    $u['id']=$rowID;
    $u['line']=$nextLineNumberForThisUser;
    $userTracker[$userNumber]=$nextLineNumberForThisUser;
}


foreach ($toUpdate as $row){
    $id=$row['id'];
    $line=$row['line'];
    mysql_query("UPDATE `$table` SET `line`='$line' WHERE `id`='$id'");
}
?>

答案 1 :(得分:0)

MySQL解决方案

update 
  table_name t,
  ( select 
        id, user, line
      , case when @prev=(@curr:=user)
             then @row_num:=(@row_num + 1)
             else @row_num:=1
        end as unique_user_row_num
      , @prev:=@curr as temp_curr
    from table_name,
         (select @prev:='', @curr:='', @row_num:=0) row_nums
  ) d
set 
  t.line = d.unique_user_row_num
where 
  t.id=d.id
;

演示 @ MySQL 5.5.32 Fiddle