Mysql - 在表中插入只有一个自动递增列

时间:2011-05-11 09:28:45

标签: mysql

假设我们表A只有一列,id(这是主键)

如何在不指定ID的情况下在表中插入新行?

我试过这个

INSERT INTO A (`id`) VALUES (NULL)

它不起作用

编辑:我忘了提到id,主键有auto_increment和NOT NULL属性。

编辑2:运行上述查询时的确切错误是

Column 'id' cannot be null

5 个答案:

答案 0 :(得分:12)

只要'id'作为自动增量启用(假设ID是整数),您就可以这样做:

INSERT INTO A (id) values (null)

和'id'每次都会递增。

答案 1 :(得分:3)

仅在您使用auto_increment主键(PK)时才有效,因为每个PK必须具有唯一的非空值。

drop table if exists A;
create table A
(
id int unsigned not null auto_increment primary key
)
engine=innodb;

insert into A (id) values (null),(null);

mysql> select * from A order by id;
+----+
| id |
+----+
|  1 |
|  2 |
+----+
2 rows in set (0.00 sec)

答案 2 :(得分:0)

尝试没有``.. 如:

INSERT INTO(sid)VALUES(NULL); //我使用sid而不是id ...

对我来说很好..

同时创建表A,指定unique(sid)... 即

创建表A(sid int(3)not null auto_increment unique(sid));

答案 3 :(得分:0)

我有类似的问题,然后我注意到当我将id更改为主键+非null +自动增量时,我没有应用更改。

答案 4 :(得分:0)

INSERT INTO `table` () VALUES (); 

也在工作。

相关问题