MySQL auto_increment

时间:2010-08-02 05:10:57

标签: mysql auto-increment

我有这张桌子

CREATE TABLE `zipcodes2` (
  `ID` int(11) NOT NULL auto_increment,
  `zipcode` int(6) NOT NULL default '0',
  `State` char(3) NOT NULL default '',
  `zip_name` varchar(255) NOT NULL default '',
  `CityAliasName` varchar(255) NOT NULL default '',
  `latitude` float(26,7) NOT NULL default '0.0000000',
  `longitude` float(36,7) NOT NULL default '0.0000000',
  `AreaCode` smallint(3) NOT NULL default '0',
  `County` varchar(255) NOT NULL default '',
  `TimeZone` smallint(3) NOT NULL default '0',
  `DayLightSavings` char(2) NOT NULL default '',
  PRIMARY KEY  (`zipcode`,`CityAliasName`,`ID`),
  KEY `CityAliasName` (`CityAliasName`),
  KEY `State` (`State`),
  KEY `index_by_zipcode` (`zipcode`),
  KEY `index_by_state` (`State`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

我正试图从另一个表中插入此表。问题是auto_increment字段没有递增。我做错了什么?

insert into zipcodes2 (ID,zipcode,state,zip_name,CityAliasName,latitude,longitude, AreaCode, County, TimeZone, DayLightSavings)
select distinct null,ZipCode as zipcode,State as state,City as zip_name, CityAliasName, Latitude as latitude, Longitude as longitude, AreaCode
, County, TimeZone, DayLightSavings
from zip_codes_all  
where state NOT in ('PR', 'AE', 'PW', 'MP', 'GU', 'FM', 'AS','AP', 'AA','FM','GA','GU','FM')
limit 0,10;

4 个答案:

答案 0 :(得分:0)

尝试从查询中删除“ID”:

insert into zipcodes2 (zipcode,state,zip_name,CityAliasName,latitude,longitude, AreaCode, County, TimeZone, DayLightSavings)
select distinct ZipCode as zipcode,State as state,City as zip_name, CityAliasName, Latitude as latitude, Longitude as longitude, AreaCode, County, TimeZone, DayLightSavings
from zip_codes_all  
where state NOT in ('PR', 'AE', 'PW', 'MP', 'GU', 'FM', 'AS','AP', 'AA','FM','GA','GU','FM')
limit 0,10;

答案 1 :(得分:0)

问题是,

PRIMARY KEY(zipcodeCityAliasNameID

应该是,

PRIMARY KEY(ID

一旦我改变了它,并从插入中移除了ID字段,我得到了我期待的结果。

答案 2 :(得分:0)

是的,主键定义是关键。 正如mysql文档所说:

  

对于MyISAM和BDB表,您可以   在辅助节点上指定AUTO_INCREMENT   多列索引中的列。在   这种情况下,生成的值为   AUTO_INCREMENT列计算为   MAX(auto_increment_column)+ 1 WHERE   前缀=给定前缀。这很有用   当你想把数据放入有序的时候   基团。

在修复主键之前,你的id可能有非唯一值。

答案 3 :(得分:0)

你应该添加:

PRIMARY KEY ON ID COLUMN AND AUTOINCREMENT