键"PRIMARY"的条目"0"重复 [英] Duplicate entry '0' for key 'PRIMARY'

查看:152
本文介绍了键"PRIMARY"的条目"0"重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白为什么尝试填充此表时会收到此错误.此刻表中什么都没有,所以我不明白为什么会有重复...

I don't understand why I'm getting this error when trying to populate this table. There is nothing in the table at the moment so I don't understand why there would be a duplicate...

这是我正在使用的代码:

This is the code I'm using:

INSERT INTO Suppliers
(supp_id,company_name,town,phone)
Values
("ADT217","AdTec","Birmingham","0121-368-1597"),
("CPS533","CPS","Maidenhead","01382-893715"),
("FCL162","ForComp Ltd","Nottingham","01489-133722"),
("KBC355","KBC Computers","Glasgow","0141-321-1497");

任何帮助将不胜感激,

谢谢.

供应商表...

CREATE TABLE suppliers(
    supp_id int NOT NULL,
    company_name character(15) NOT NULL,
    town character(15)
    phone character(15)
primary key(supp_id)
);

推荐答案

当您有主键但没有给它提供初始化值时,会发生这种情况.插入本身会导致重复.

This occurs when you have a primary key but do not give it an initialization value. The insert itself is causing the duplication.

在您的情况下,我想到了两种可能性:

In your case, two possibilities come to mind:

  1. supp_id是主键,并声明为数字.在旧版本的MySQL中,我认为字符串值会默默地转换为数字.因为前导字符是字母,所以该值为0.

  1. supp_id is the primary key and declared as a number. In older versions of MySQL, I think the string values get silently converted to numbers. Because the leading characters are letters, the value is 0.

您还有另一个id字段,它是主键,但是没有给出值且未声明auto_increment.

You have another id field that is the primary key, but given no value and not declared auto_increment.

我怀疑您需要以下代码:

I suspect you want the following code:

CREATE TABLE suppliers (
    supplierId int NOT NULL auto_increment primary key,
    supp_name varchar(255) unique,
    company_name varchar(15) NOT NULL,
    town varchar(15),
    phone varchar(15)
);

INSERT INTO Suppliers(supp_name, company_name, town, phone)
    Values ('ADT217', 'AdTec', 'Birmingham', '0121-368-1597'),
           ('CPS533', 'CPS', 'Maidenhead', '01382-893715'),
           ('FCL162', 'ForComp Ltd', 'Nottingham', '01489-133722'),
           ('KBC355', 'KBC Computers', 'Glasgow', '0141-321-1497');

一些注意事项:

  • 通常,您希望使用varchar()而不是char(),除非您真的很喜欢字符串末尾的空格.
  • 我在表中添加了唯一的供应商名称,并声明该ID为auto_increment.
  • 单引号是用于字符串常量的ANSI标准. MySQL(和其他一些数据库)允许使用双引号,但是没有理由不使用该标准.
  • Usually you want varchar() rather than char(), unless you really like lots of spaces at the end of strings.
  • I added a unique supplier name to the table and declared the id to be a auto_increment.
  • Single quotes are ANSI standard for string constants. MySQL (and some other databases) allow double quotes, but there is no reason to not use the standard.

这篇关于键"PRIMARY"的条目"0"重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆