Home  >  Article  >  Database  >  How to create foreign key constraints in mysql

How to create foreign key constraints in mysql

王林
王林Original
2020-10-13 16:41:2010738browse

Mysql method to establish foreign key constraints: directly execute the [CREATE TABLE stu(sid INT PRIMARY KEY,NAME VARCHAR(50) NOT NULL);] statement.

How to create foreign key constraints in mysql

Add foreign key constraints

(Recommended tutorial: mysql video tutorial)

CREATE TABLE stu(
    sid INT PRIMARY KEY,
    NAME VARCHAR(50) NOT NULL
);

Add foreign key constraint method one

CREATE TABLE score1(
    score DOUBLE,
    sid INT,
    CONSTRAINT fk_stu_score1_sid FOREIGN KEY(sid) REFERENCES stu(sid)
);

Add foreign key constraint method two (if the table already exists, you can use this method)

CREATE TABLE score1(
    score DOUBLE,
    sid INT
);
ALTER TABLE score1 ADD CONSTRAINT fk_sid FOREIGN KEY(sid) REFERENCES stu(sid)

Related recommendations: mysql tutorial

The above is the detailed content of How to create foreign key constraints in mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn