0

我正在尝试将增量值添加到表中的新列。这是表的示例结构

---------------------
Name - class - id
---------------------
abbc - 2     - null
efg  - 4     - null
ggh  - 6     - null
---------------------

我想编写一个查询,该查询将为表中的所有记录生成唯一 ID 这是我尝试过但显示为空的查询

set @i=0;
update table1 set id =(@i:=@i+1);
4

4 回答 4

3

What you have shown should work; the id column should be getting assigned values.

I tested your statement; I verified it works on my database. Here's the test case I ran:

CREATE TABLE table1 (`name` VARCHAR(4), class TINYINT, id INT);
INSERT INTO table1 (`name`,class) VALUES ('abbc',2),('efg',4),('ggh',6);
SET @i=0;
UPDATE table1 SET id =(@i:=@i+1);
SELECT * FROM table1;

Note that MySQL user variables are specific to a database session. If the SET is running in one session, and the UPDATE is running another session, that would explain the behavior you are seeing. (You didn't mention what client you ran the statements from; most clients reuse the same connection, and don't churn connections for each statement, I'm just throwing that out as a possibility.)

To insure that @i variable is actually initialized when the UPDATE statement runs, you can do the initialization in the UPDATE statement by doing something like this:

UPDATE table1 t
 CROSS
  JOIN (SELECT @i := 0) s
   SET t.id =(@i:=@i+1);

I tested that, and that also works on my database.

于 2014-02-24T05:40:07.383 回答
1

试试这个查询我的朋友:

set @i=0;
update table1 set id =(select @i:=@i+1);

SQL小提琴

于 2014-02-24T05:20:40.230 回答
0
SET @a = 0;  
UPDATE table_name SET id = @a:=@a+1;
于 2014-02-24T05:24:50.663 回答
-1

对相应的列使用 AUTOINCREMENT 参数。此参数将在相应列中放置一个唯一的自动递增值。

于 2014-02-24T05:16:23.250 回答