2014-04-25 69 views
0

我在MySQL下表:更新与一个递增值的字段用于复位基于字段

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

我需要更新线列是一个递增的数字,对于每个用户重置,所以我woudl结束与此:

|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中做到这一点?

+0

是你打开与PHP解决? –

+0

@AndreasStorvikStrauman - 当然...在MySQL是首选,但PHP的作品。 – Jason

+0

好的。如果您可以详细说明为什么要实现这一目标,我们可能会找到一种替代解决方案。我会为你写一个PHP解决方案的答案:) –

回答

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:[email protected] 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

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'"); 
} 
?> 
+0

看起来像这样的工作,但我会去@Ravinder的答案,因为它是一个SQL解决方案。考虑到我有> 5000条记录需要处理,PHP解决方案有点慢。 – Jason

+0

当然,你必须回答你的问题! :) –