[英]mysql AUTO_INCREMENT based on another column
How can I auto increment id
column based on the 0 to max (int) value on the price
column. 如何根据
price
列上的0到最大值(int)自动增加id
列。
Lets assume that price is ASC
, I want the id = 1
increment to start at the $0 mark. 假设
price is ASC
,我希望id = 1
增量从$ 0开始。 What would I have to edit for this code ALTER TABLE table AUTO_INCREMENT = 1
? 我需要为该代码
ALTER TABLE table AUTO_INCREMENT = 1
什么?
id | price | other columns
1 | 9
2 | 1
3 | 2
4 | 5
into 进入
id | price | other columns
1 | 1
2 | 2
3 | 5
4 | 9
A easy Way ist to create a new table with one column more with autoincrement. 一种简单的方法,可以使用自动增量功能创建一个新的表格,该表格多一列。
intert into newtable select '',o.* from oldtable o order by o.price asc;
Then they insert all row in the right order from price in the new table. 然后他们以正确的顺序将所有行从价格插入新表中。
如果您只想使用具有rownumber的行,则可以这样做:
SELECT @nr:=@nr+1 AS id,c.* FROM mytable c, (SELECT @nr:=0) tmp;
the feld x is NOT autoincrement. feld x不是自动递增。 its only a non uniqe index
它只是一个非唯一索引
SET @nr:=0;
UPDATE newtable n SET n.x = @nr:=@nr+1 ORDER BY n.price ASC;
sorry, you must send 2 Querys. 抱歉,您必须发送2条查询。 The first to set rhe Variable nr to 0 and then the update statement
首先将rhe Variable nr设置为0,然后设置update语句
SET @nr:=0;
UPDATE your_table_name t
SET t.id = @nr:=@nr+1
ORDER BY t.price ASC;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.