2011-09-06 23 views
3

下面的MySQL語句正常工作,它將每行結果的行數返回給我。但是現在,我想要做的是使用update語句將列pos設置爲「row」的值,因爲我不想用單個查詢循環數千條記錄。更新語句中的MySQL行計數器

任何想法?

SELECT @row := @row + 1 AS row, u.ID,u.pos 
FROM user u, (SELECT @row := 0) r 
WHERE u.year<=2010 
ORDER BY u.pos ASC LIMIT 0,10000 
+1

絕對有可能。 [看到這個答案](http://stackoverflow.com/questions/7299400/interpolate-missing-values-in-a-mysql-table/7299650#7299650) –

回答

1

There is a risk using user defined variables

在SELECT語句中,當發送到客戶機的每個選擇表達式僅被評估。這意味着,在HAVING,GROUP BY,或ORDER BY子句,指的是在選擇表達式列表分配一個值不按預期的變量:

一個更安全防範方法是

create table tmp_table 
(
    pos int(10) unsigned not null auto_increment, 
    user_id int(10) not null default 0, 
    primary key (pos) 
); 

insert into tmp_table 
select null, u.ID 
from user 
where u.year<=2010 
order by YOUR_ORDERING_DECISION 
limit 0, 10000; 

alter table tmp_table add index (user_id); 

update user, tmp_table 
set user.pos=tmp_table.pos 
where user.id=tmp_table.user_id; 

drop table tmp_table;