Question

I have a table with column1 set as primary key. I believe it therefore have unique constraint and index on it. Now I want to introduce column2 as the new primary key, but I want to keep column1 as a secondary key with unique constraint and index on it. The question is: if I will execute

alter table my_table drop primary key;

will it remove unique constraint and/or index from column1 in MySQL (InnoDB)?

Était-ce utile?

La solution

Yes it will drop existing primary key. You can try like below

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)

Autres conseils

Apperent, yes it will remove the unique constraint and the index.

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

And when you alter the table.

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

 Record Count: 0; Execution Time: 1ms

These statements will be allowed when you dropped the primary key..

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

Here's a SQL Fiddle

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top