2013-08-28 62 views
1

我需要通過它們的編號更新行(不是AI ID,導致某些行可能會被刪除)。我怎樣才能做到這一點? 我的意思是這樣:MySQL更新行號

UPDATE cars SET idx = value WHERE row_number = i 

我會在「for」語句做到這一點,我是我發言的整數。所以我會更新聲明中的每一行。

對不起,我的英語不好,謝謝!

+0

您正在使用哪種腳本語言? ,PHP? – bhawin

+0

嗯...我使用典當,但一個php解決方案也可以幫助 –

回答

2

這裏是一個純粹的MySQL解決方案:

/*test data*/ 
create table foo (id int auto_increment primary key, a int); 
insert into foo (a) values (10), (11), (12); 

/*update statement*/ 
update foo 
set a = 5 
where id = (
    select id from (
     select id, @rownum:[email protected] + 1 as rownumber 
     from foo, (select @rownum:=0) vars order by id 
    ) sq where rownumber = 2 
); 

結果:

| ID | A | 
-----|----|-- 
| 1 | 10 | 
| 2 | 5 | 
| 3 | 12 | 

隨意問你是否對此有任何疑問。

此外,請注意在那裏的order by id。這很重要,因爲在數據庫中沒有第一行或最後一行。從理論上說,如果沒有訂單條款,每次都會有不同的結果。

你也可以看到它working live here in an sqlfiddle

+0

@AdamSchauer bhawin的解決方案不確定,因此容易出錯。請考慮我的解決方案。 – fancyPants

+0

非常感謝sqlfiddle鏈接!現在我可以弄明白了。順便說一句。 SQL中'@'意味着什麼?我從來沒有見過它。 –

+0

它用於用戶定義的變量。你可以在這裏閱讀更多關於它們的信息:http://dev.mysql.com/doc/refman/5.0/en/user-variables.html – fancyPants

0

我不知道這對MySQL的,但你可以在PHP

$row_number=? ;//the row no of mysql you want to change the id 
$id=? ;//the new id 
mysql_connect //do it yourself 
$query="select 8 from tablename"; //the query 
$result=mysql_query($qyery,$conn); 
$count=0; 
while($row=mysql_fetch_array($result)) // fetch each row one by one an put data in array $row 
{ 
    $count++;  //increment count means the no of rows are incermented 
    if($count==$rownumber) //the row where you want to edit the id 
    { 
     $query1="update tablename set id='".$id."' where id=".$row["id"]; //new query on that particular row 
     $result1=mysql_query($query1,$conn); 
    } 
} 

這將工作做到這一點,根據自己的使用只需要修改這個代碼

+0

thnx很多人,我只是編了代碼,很高興它解決了你的問題 – bhawin