MYSQL - What is a primary key?

限于喜欢 提交于 2020-01-03 16:57:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!