Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
90 views
in Technique[技术] by (71.8m points)

sql - Removing a Key from MySQL Table

I am trying to remove the city from this MySQL table -

mysql> desc Persons;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| PersonID  | int(11)      | NO   | PRI | NULL    |       |
| LastName  | varchar(255) | NO   | PRI | NULL    |       |
| FirstName | varchar(255) | NO   | PRI | NULL    |       |
| Address   | varchar(255) | YES  |     | NULL    |       |
| City      | varchar(255) | NO   | PRI | NULL    |       |
+-----------+--------------+------+-----+---------+-------+

Now city along with 3 other attributes happens to be a primary key and when I execute -

mysql> ALTER TABLE Persons DROP PRIMARY KEY;

It will remove all the Primary Keys.

mysql> DESC Persons;
+-----------+--------------+------+-----+---------+-------+
| Field     | Type         | Null | Key | Default | Extra |
+-----------+--------------+------+-----+---------+-------+
| PersonID  | int(11)      | NO   |     | NULL    |       |
| LastName  | varchar(255) | NO   |     | NULL    |       |
| FirstName | varchar(255) | NO   |     | NULL    |       |
| Address   | varchar(255) | YES  |     | NULL    |       |
| City      | varchar(255) | NO   |     | NULL    |       |
+-----------+--------------+------+-----+---------+-------+

But now when I am adding all the keys back without the city, it's giving an error -

mysql> ALTER TABLE Persons ADD PRIMARY KEY(PersonID, LastName, FirstName);
ERROR 1062 (23000): Duplicate entry '100-SINHA-VED' for key 'PRIMARY'

Now due to duplicate values in the table, in which only city was different, I can't make the other 3 as primary keys and also I can't delete the data as the problem is on some other table, can't expose the table, so made this sample table "Persons" and replicated the problem.

How to tackle this problem, have never encountered it before.

question from:https://stackoverflow.com/questions/65887219/removing-a-key-from-mysql-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as, I understand your problem. I think composite keys might be the solution for this problem. I guess, click here for more info.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...