删除 MySQL 中的主键

时间:2021-08-01 21:50:17

标签: mysql sql

当我尝试从表中删除主键时收到此错误:

00:44:25    ALTER TABLE BOOKS DROP PRIMARY KEY  Error Code: 1075. Incorrect table definition; there can be only one auto column and it must be defined as a key 0.000 sec.

下面是我的代码

CREATE DATABASE IF NOT EXISTS BD3;   
USE BD3;

# creare tabele Carti si Library

CREATE TABLE IF NOT EXISTS Books(
id TINYINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
titlu VARCHAR(20) NOT NULL,
autor VARCHAR(25) NOT NULL,
data_aparitie DATE NOT NULL,
editura VARCHAR(15),
gen ENUM('drama', 'SF') NOT NULL

);

ALTER TABLE Books DROP PRIMARY KEY;

2 个答案:

答案 0 :(得分:5)

AUTO_INCREMENT 列必须是键。所以如果要去掉主键索引,首先要去掉这个选项。

ALTER TABLE Books MODIFY id TINYINT NOT NULL, DROP PRIMARY KEY;

答案 1 :(得分:1)

您的错误消息说明 AUTO_INCREMENT 列必须是键,因此您必须将两者都删除

你能做什么

首先从表中删除 auto_incement 和 Proiary Key

DROP 索引,然后添加 KEY 和 AUTO_INCREMENT

CREATE TABLE IF NOT EXISTS Books (
    id TINYINT NOT NULL PRIMARY KEY AUTO_INCREMENT,
    titlu VARCHAR(20) NOT NULL,
    autor VARCHAR(25) NOT NULL,
    data_aparitie DATE NOT NULL,
    editura VARCHAR(15),
    gen ENUM('drama', 'SF') NOT NULL
);

ALTER TABLE books
  MODIFY id TINYINT NOT NULL;

ALTER TABLE Books DROP PRIMARY KEY;

ALTER TABLE books
  MODIFY id TINYINT NOT NULL  KEY AUTO_INCREMENT;