Skip to main content

Posts

Showing posts from June, 2019

Creating a foreign key in MySQL

The idea behind foreign key in a database is that one table relates to another table. The common example is that you may have a table containing users which has these fields:id: The ID of the username: The full name of the useremail: The email address of the userThen you may have a table with purchases, which links to the user table:id: The ID of the purchasedate: The date of the purchaseitem: The item purchasedprice: The price of the itemuser_id: The id of the userTechnically, you don’t have to link both tables. You could fill the user_id field with an idea from the users’ table and just assume it’s valid. But adding it as a foreign key just makes sure that the database will enforce that the id actually exists in the other table.This is how you can create the two tables:CREATE TABLE users (id VARCHAR(20) UNIQUE NOT NULL PRIMARY KEY, name VARCHAR(200), email VARCHAR(50)); CREATE TABLE purchases (id VARCHAR(20), date VARCHAR(20), item VARCHAR(50), price BIGINT, user_id VARCHAR(20)…