繁体   English   中英

MySQL:删除主键是否会删除唯一约束和/或索引?

[英]MySQL: Does dropping primary key removes unique constraint and/or index?

我有一个将column1设置为主键的表。 因此,我认为它具有唯一的约束和索引。 现在,我想将column2引入为新的主键,但我想保留column1作为具有唯一约束和索引的辅助键。 问题是:我是否要执行

alter table my_table drop primary key;

它会从MySQL(InnoDB)的column1中删除唯一约束和/或索引吗?

是的,它将删除现有的主键。 您可以尝试如下

DROP TABLE IF EXISTS test_index;
Query OK, 0 rows affected (0.04 sec)

CREATE TABLE test_index(ID INT , PRIMARY KEY(ID));
Query OK, 0 rows affected (0.25 sec)

ALTER TABLE test_index ADD COLUMN email CHAR(50) NOT NULL;
Query OK, 0 rows affected (0.33 sec)
Records: 0  Duplicates: 0  Warnings: 0

ALTER TABLE test_index DROP PRIMARY KEY , ADD UNIQUE KEY (ID) , ADD PRIMARY KEY(email);
Query OK, 0 rows affected (0.48 sec)
Records: 0  Duplicates: 0  Warnings: 0

show create table test_index\G
*************************** 1. row ***************************
           Table: test_index
    Create Table: CREATE TABLE `test_index` (
      `ID` int(11) NOT NULL DEFAULT '0',
      `email` char(50) NOT NULL,
      PRIMARY KEY (`email`),
      UNIQUE KEY `ID` (`ID`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8
    1 row in set (0.00 sec)

显然,是的,它将删除唯一约束和索引。

CREATE TABLE IF NOT EXISTS my_table(
  col1 INT PRIMARY KEY,
  col2 INT);

SHOW INDEX FROM my_table;

|    TABLE | NON_UNIQUE | KEY_NAME | SEQ_IN_INDEX | COLUMN_NAME | COLLATION | CARDINALITY | SUB_PART | PACKED | NULL | INDEX_TYPE | COMMENT | INDEX_COMMENT |
|----------|------------|----------|--------------|-------------|-----------|-------------|----------|--------|------|------------|---------|---------------|
| my_table |          0 |  PRIMARY |            1 |        col1 |         A |           0 |   (null) | (null) |      |      BTREE |         |               |

当您更改表格时。

alter table my_table drop primary key;
SHOW INDEX FROM my_table;

 Record Count: 0; Execution Time: 1ms

当您删除主键时,将允许使用这些语句。

INSERT INTO my_table VALUES (1,1);
INSERT INTO my_table VALUES (1,1);

这是一个SQL小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM