【问题标题】:mysql can't insert record with unsigned primary key being zeromysql无法插入无符号主键为零的记录
【发布时间】:2013-05-14 17:44:49
【问题描述】:

我正在尝试将一条记录插入到 dim_channel 表中,主键为零(无符号整数)。

Mysql 命令:

INSERT INTO dim_channel 
set channel_id=0,name='Other',parent_channel_id=0,parent_channel_name='Other';

结果:

select * from dim_channel;
+------------+-------+-------------------+---------------------+
| channel_id | name  | parent_channel_id | parent_channel_name |
+------------+-------+-------------------+---------------------+
|          1 | Other |                 0 | Other               |
+------------+-------+-------------------+---------------------+

请注意,channel_id 的值为 1,而不是我预期的 0。

任何人都知道为什么会这样。

顺便说一句,我可以将记录更新为: update dim_channel set channel_id=0 where channel_id=1;

只想知道为什么我一开始就不能插入channel_id=0的记录。

非常感谢。

====== MySQL 命令供你测试====

-- 创建表

CREATE TABLE `dim_channel` (
  `channel_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` char(80) DEFAULT NULL,
  `parent_channel_id` int(10) unsigned NOT NULL DEFAULT '0',
  `parent_channel_name` varchar(80) DEFAULT NULL,
  PRIMARY KEY (`channel_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1

--插入记录

INSERT INTO dim_channel set channel_id=0,name='Other',parent_channel_id=0,parent_channel_name='Other';

--查看结果

select * from dim_channel;

【问题讨论】:

  • mysql 假设 0 表示 auto_increment 列的“给我下一个 ID”。如果你真的想要一个不属于它的 0,那么在插入之后使用更新。
  • @user645280 很棒的评论!

标签: mysql insert


【解决方案1】:

我知道这是一篇旧帖子,但无论如何:

用途:

SET sql_mode='NO_AUTO_VALUE_ON_ZERO';

在您的维度中插入 0 值之前。

【讨论】:

  • 非常有帮助。以供将来参考,这是在正在执行的 SQL 中设置,还是可以将其设置为 MySQL 中的永久配置选项?
【解决方案2】:

这是因为您在该字段上有一个自动递增的主键。如果您在插入时为该值分配 NULL0,它将显式为您提供表序列中的下一个数字。

【讨论】:

  • 谢谢。看来我必须使用两个mysql命令来插入这条记录。
  • @user1828513 请注意,如果您的意图是能够输入 0 作为多条记录的值,您将无法在此字段上拥有主键或非空唯一索引.我当然会首先考虑您为什么要这样做,并考虑将自动增量主键字段值设置为 0 是否真的是表示您试图在数据中表示的任何内容的最佳方法。跨度>
  • @MikeBrant 希望他不想将 0 插入多行,这样做会完全打破“id”的概念
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-04
  • 1970-01-01
相关资源
最近更新 更多