Duplicate entry '0' for key 'PRIMARY'

前端 未结 2 1670
孤独总比滥情好
孤独总比滥情好 2021-01-25 18:41

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 dupli

2条回答
  •  终归单人心
    2021-01-25 19:20

    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 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.

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

    EDIT:

    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');
    

    Some notes:

    • 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.

提交回复
热议问题