Languages
[Edit]
EN

MySQL - create table with FOREIGN KEY

0 points
Created by:
WGates
412

In this article, we would like to show you how to create a table with FOREIGN KEY in MySQL.

Quick solution:

Note:

Go to the official documentation to see available DATA_TYPES.

Practical example

Edit

In this example, we will create two tables:

  • groups table with two columns:
    • id- with PRIMARY KEY constraint
    • group_name

and users table with three columns:

  • id - with PRIMARY KEY constraint
  • username
  • group_id - which will be our FOREIGN KEY with groups.id column reference

Query:

Result:

MySQL - create a table with PRIMARY KEY
MySQL - create a table with PRIMARY KEY
MySQL - create a table with FOREIGN KEY
MySQL - create a table with FOREIGN KEY

As we see in the second picture, the group_id column from users table has FOREIGN KEY constraint which refers to the id column from groups table with PRIMARY KEY constraint.

References

Edit
1
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

MySQL - Problems

MySQL - Create table with FOREIGN KEY
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join