#1062 eror in mysql

96 Views Asked by At

I got a 1062 error in this code :

CREATE DATABASE IF NOT EXISTS `phppoll` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
USE `phppoll`;

CREATE TABLE IF NOT EXISTS `polls` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `title` text NOT NULL,
    `description` text NOT NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

INSERT INTO `polls` (`id`, `title`, `description`) VALUES (1, 'What''s your favorite programming language?', '');

CREATE TABLE IF NOT EXISTS `poll_answers` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `poll_id` int(11) NOT NULL,
    `title` text NOT NULL,
    `votes` int(11) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

INSERT INTO `poll_answers` (`id`, `poll_id`, `title`, `votes`) VALUES (1, 1, 'PHP', 0), (2, 1, 'Python', 0), (3, 1, 'C#', 0), (4, 1, 'Java', 0);

I don't no how fix it.

1

There are 1 best solutions below

0
Progman On

The problem arise when you run this SQL script and your target database already have the tables you want to create AND it has rows with already used ids. The INSERT INTO statements will fail of duplicate keys.

Depending on what you want to do or how you want to create a backup or restore it, you can use several options:

  1. You can delete the existing tables, so they will be added when the SQL script is executed. They will obviously be empty when the tables are added.
  2. You can delete all the existing rows in your tables. When you run your SQL script, the tables will not be created due to the IF NOT EXISTS part, but the tables will be empty.
  3. You can create a MySQL dump with statements which will delete existing tables (and therefore delete any rows). For the mysqldump command, there is a setting --add-drop-table to do that. Other MySQL export programs might have similar options.