[英]MySQL Update by Row number
I need to update rows by their number(not AI ID, cause some of the rows may will be removed). 我需要按行号更新行(不是AI ID,因为某些行可能会被删除)。 How can I do this?
我怎样才能做到这一点? I mean something like this:
我的意思是这样的:
UPDATE cars SET idx = value WHERE row_number = i
I would do this in a 'for' statement, and i is the integer of my statement. 我会在“ for”语句中执行此操作,并且我是语句的整数。 So I would update every row in the statement.
因此,我将更新语句中的每一行。
Sorry for my bad english, and thanks! 对不起,我的英语不好,谢谢!
Here's a pure MySQL solution: 这是一个纯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:=@rownum + 1 as rownumber
from foo, (select @rownum:=0) vars order by id
) sq where rownumber = 2
);
Results in: 结果是:
| ID | A |
-----|----|--
| 1 | 10 |
| 2 | 5 |
| 3 | 12 |
Feel free to ask if you have any questions about this. 随时询问您是否对此有任何疑问。
Also, note the order by id
in there. 另外,请注意其中
order by id
。 It's important, cause in a database there is no first or last row. 这很重要,因为在数据库中没有第一行或最后一行。 Without an order by clause theoretically there could be each time a different result.
理论上,如果没有按顺序排列的子句,每次都会有不同的结果。
You can also see it working live here in an sqlfiddle . 您也可以在sqlfiddle中看到它的实时运行 。
i don't know this about mysql but you can do this in php 我不知道有关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);
}
}
this will work , just modify this code according to your use 这将起作用,只需根据您的使用修改此代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.