[英]Auto_increment Column does not create while updating table query
I create a table whose query is 我创建一个表,其查询是
Create table unititem (ID INT NOT NULL AUTO_INCREMENT, PRIMARY KEY (ID));
than alter it by following query 比通过以下查询更改它
Alter table unititem AUTO_INCREMENT=1;
I also have a table tablename
and in want to alter it by adding a column unitItemId
which references table unititem
. 我也有一个表tablename
并且想要通过添加引用表unititem
列来unitItemId
进行unititem
。 The query which I want to execute is 我要执行的查询是
Alter table tablename add column Unititemid INT NOT
NULL AUTO_INCREMENT ;
but when I execute this query it gives me this error: 但是当我执行此查询时,它给了我这个错误:
Incorrect table definition; 表定义不正确; there can be only one auto column and it must be defined as a key 只能有一个自动列,并且必须将其定义为键
When I want to make it a foreign key then it gives 1005 error
on following query 当我想使其成为外键时,它在以下查询中给出1005 error
Alter table tablename
add column Unititemid INT NOT NULL AUTO_INCREMENT,
ADD FOREIGN KEY (Unititemid) REFERENCES unititem (ID) ;
I don't know what I'm doing wrong. 我不知道我在做什么错。 Any suggestions? 有什么建议么?
Update1 As suggested I'm not adding unititemid
as AUTO_INCREMENT
Update1如建议的那样,我没有将unititemid
添加为AUTO_INCREMENT
ALTER TABLE tablename ADD COLUMN unititemid INT NOT NULL;
Now the problem is: how can I make it a foreign key? 现在的问题是:如何使其成为外键? When i use the following query it gives an error: 当我使用以下查询时,它给出一个错误:
ALTER TABLE tablename ADD FOREIGN KEY (unititemid) REFERENCES unititem(ID);
Error: Error Code: 1005 Can't create table 'alnasar_inventory.#sql-a04_1' (errno: 150) 错误:错误代码:1005无法创建表“ alnasar_inventory。#sql-a04_1”(错误号:150)
howto resolve this issue ? 如何解决这个问题? Any Suggestions. 有什么建议么。
To fix the query, simply remove AUTO_INCREMENT
. 要解决此查询,只需删除AUTO_INCREMENT
。 Try: 尝试:
Alter table tablename add column Unititemid INT NOT
NULL ;
You don't want (and cannot have) the foreign key to auto increment in your new table. 您不希望(也不能拥有)外键在新表中自动递增。
AUTO_INCREMENT
exists to automatically generate a new unique id for your table row, but it doesn't make sense to use it on a foreign key. 存在AUTO_INCREMENT
可以自动为您的表行生成一个新的唯一ID,但是在外键上使用它没有任何意义。
Consider the table unititem
. 考虑表unititem
。 It has id's 1
, 2
, 3
. 它有ID的1
, 2
, 3
。 You also have 3 rows in tablename
with Unititemid
's 1
, 2
, 3
. 您还可以在3行tablename
与Unititemid
的1
, 2
, 3
。 Now you create a new row in the other table tablename
. 现在,您在另一个表tablename
创建一个新行。 How would you expect AUTO_INCREMENT
to work here? 您希望AUTO_INCREMENT
在这里工作如何? It would auto increment 3
to 4
but that doesn't make any sense because there is no 4
in unititem. 它将自动将3
递增到4
但这没有任何意义,因为unititem中没有4
。 So AUTO_INCREMENT
only makes sense on the original table, not on the other table. 因此, AUTO_INCREMENT
仅在原始表上有意义,而在另一个表上则没有意义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.