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
744 views
in Technique[技术] by (71.8m points)

mysql - Difference between Unique Key and Primary Keys

I came across the following SQL in a book:

CREATE TABLE 'categories'(
id SMALLINT NOT NULL AUTO INCREMENT,
category VARCHAR(30) NOT NULL,
PRIMARY KEY('id'),
UNIQUE KEY 'category'('category')
)ENGINE=MyISAM DEFAULT CHARSET = utf8;

I was wondering is there a reason why I would need a PRIMARY and UNIQUE KEY in the same table? I guess, underlying that question is, what is the difference between PRIMARY and UNIQUE keys?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The relational model says there's no essential difference between one key and another. That is, when a relation has more than one candidate key, there are no theoretical reasons for declaring that this key is more important than that key. Essentially, that means there's no theoretical reason for identifying one key as a primary key, and all the others as secondary keys. (There might be practical reasons, though.)

Many relations have more than one candidate key. For example, a relation of US states might have data like this.

State      Abbr      Postal Code
--
Alabama    Ala.      AL
Alaska     Alaska    AK
Arizona    Ariz.     AZ
...
Wyoming    Wyo.      WY

It's clear that values in each of those three columns are unique--there are three candidate keys.

If you were going to build a table in SQL to store those values, you might do it like this.

CREATE TABLE states (
  state varchar(15) primary key,
  abbr varchar(10) not null unique,
  postal_code char(2) not null unique
);

And you'd do something like that because SQL doesn't have any other way to say "My table has three separate candidate keys."

I didn't have any particular reason for choosing "state" as the primary key. I could have just as easily chosen "abbr" or "postal_code". Any of those three columns can be used as the target for a foreign key reference, too.

And as far as that goes, I could have built the table like this, too.

CREATE TABLE states (
  state varchar(15) not null unique,
  abbr varchar(10) not null unique,
  postal_code char(2) not null unique
);

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

...