问题
I'm in the process of learning Mysql, and I'm creating databases. So, after looking at several websites, the definition for a primary key is:
The PRIMARY KEY constraint uniquely identifies each record in a database table.
and is used like this:
CREATE TABLE Persons
(
P_Id int NOT NULL,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (P_Id) //primary key is on this line
)
However, I still don't know what it's used for and why we need it. So my question is.
Can someone explain to me what a primary key is (in basic english) and why we need one and what is it used for?
Thank-you.
回答1:
A primary key is a column that is defined as uniquely identifying each row in a table.
Also, by defining a column as PRIMARY KEY
, it may be referenced as a foreign key in other tables when defining referential integrity constraints.
回答2:
A primary key is a unique identifier for the row. It is normally automatically assigned by the database management system (if you specify auto-increment for that value). So if you have a database of people in an organisation, their primary key may be their employee number. Every time you add an employee, they receive a unique employee number that is usually the previous employees number + 1.
Without primary keys you could not distinguish between two employees called john smith (without other information) Hope that is clear enough.
来源:https://stackoverflow.com/questions/9551195/mysql-what-is-a-primary-key