Home > Database > Mysql Tutorial > body text

How to create foreign key constraints in mysql

王林
Release: 2020-10-13 16:41:20
Original
10739 people have browsed it

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
);
Copy after login

Add foreign key constraint method one

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

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)
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template