[英]Insert new column, increment all rows
Is this possible using only mysql: 这可能只使用mysql:
Insert a new column and example - "pos". 插入一个新列和示例 - “pos”。 Every row in the table has to have unique,incresing value of "pos" like - 1,2,3,4,5. 表中的每一行都必须具有独特的,“pos”的值,如1,2,3,4,5。
In php this would be an easy job: 在php中这将是一件容易的事:
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$counter = 0;
while($row = mysql_fetch_array($result)){
mysql_query( "UPDATE example SET pos = ".++$counter." WHERE id = ".$row['id']." );
}
是的,你可以这样做
UPDATE example SET pos = pos+1 WHERE id = ".$row['id']."
As already suggested, the most efficient solution is to use auto incremental on pos. 如前所述,最有效的解决方案是在pos上使用自动增量。
Alternatively if your use case do not permit you, then try similar: 或者,如果您的用例不允许,请尝试类似:
"UPDATE example SET pos = ((select max(pos) from example) +1) WHERE id
= ".$row['id']."
为你的pos
mysql字段提供auto_increment
属性 - 这将对其进行索引,使其唯一,并在每个插入上递增1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.