What are primary keys and foreign keys and how are they defined in MySQL?

In MySQL, a primary key is a field used to uniquely identify a record, and a table can only have one primary key. The primary key can be a combination of one or more fields, but the contents of the fields must be unique and not empty.

In MySQL, you can define a primary key using the following syntax:

CREATE TABLE table_name (
    column1 datatype PRIMARY KEY,
    column2 datatype,
    ...
);

Foreign keys are used to establish relationships between tables by pointing to the primary key of another table. They are used to maintain data integrity and ensure that the data in related tables remains consistent.

In MySQL, you can define a foreign key using the following syntax:

CREATE TABLE table_name1 (
    column1 datatype,
    column2 datatype,
    ...
    FOREIGN KEY (column1) REFERENCES table_name2(column2)
);

Among them, table_name1 is a table containing foreign keys, column1 is the foreign key field, table_name2 is the associated table, and column2 is the primary key of the associated table.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds