DEV Community

Elham Najeebullah
Elham Najeebullah

Posted on

MySQL: How to create One-to-Many Relationship

First, I have created the necessary table in a MySQL database for an ecommerce application example:

/*The "customers" table stores information about the website's customers, including their first and last name, email, and password.*/
CREATE TABLE customers (
    customerID INT AUTO_INCREMENT PRIMARY KEY,
    firstName VARCHAR(50) NOT NULL,
    lastName VARCHAR(50) NOT NULL,
    email VARCHAR(100) NOT NULL,
    password VARCHAR(255) NOT NULL
);

/*The "categories" table stores information about different product categories, including the name of the category.*/
CREATE TABLE categories (
    categoryID INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
);

/*The "products" table stores information about the products available for purchase on the website, including their name, price, and the category they belong to.*/
CREATE TABLE products (
    productID INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    categoryID INT NOT NULL,
    FOREIGN KEY (categoryID) REFERENCES categories(categoryID)
);

/*The "orders" table stores information about orders made by customers, including the customer's ID, and the date of the order.*/
CREATE TABLE orders (
    orderID INT AUTO_INCREMENT PRIMARY KEY,
    customerID INT NOT NULL,
    orderDate DATE NOT NULL,
    FOREIGN KEY (customerID) REFERENCES customers(customerID)
);

/*The "orderDetails" table stores information about the products included in each order, including the order ID, product ID, and quantity.*/
CREATE TABLE orderDetails (
    orderID INT NOT NULL,
    productID INT NOT NULL,
    quantity INT NOT NULL,
    PRIMARY KEY (orderID, productID),
    FOREIGN KEY (orderID) REFERENCES orders(orderID),
    FOREIGN KEY (productID) REFERENCES products(productID)
);

Enter fullscreen mode Exit fullscreen mode

Each table have a key that related to other tables, for example product table related to categories table by categoryID, and order table related to customers table by customerID. Also, orderDetails table related to order table and product table by orderID and productID respectively.

The "products" table and "categories" table have a one-to-many relationship.

This is because, for each category, there can be multiple products (many products in one category), but each product can only belong to one category.

In database terms, this is represented by a foreign key on the "products" table that references the primary key of the "categories" table. This allows each row in the "products" table to be linked to a specific row in the "categories" table, creating the one-to-many relationship.

The "orders" table and "orderDetails" table have a one-to-many relationship.

This is because, for each order, there can be multiple products included (many order details), but each order detail can only belong to one order.

In database terms, this is represented by a foreign key on the "orderDetails" table that references the primary key of the "orders" table. This allows each row in the "orderDetails" table to be linked to a specific row in the "orders" table, creating the one-to-many relationship.

Still not sure. Here is a simple example
In MySQL, you can define and create a one-to-many relationship by:

  • Creating two tables: the "one" table and the "many" table.

  • Adding a foreign key column in the "many" table that references the primary key of the "one" table.

  • Using the FOREIGN KEY constraint to enforce the relationship between the two tables.

Here is an example of creating a one-to-many relationship between the "categories" table and the "products" table:

CREATE TABLE categories (
    categoryID INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(50) NOT NULL
);

CREATE TABLE products (
    productID INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    price DECIMAL(10, 2) NOT NULL,
    categoryID INT NOT NULL,
    FOREIGN KEY (categoryID) REFERENCES categories(categoryID)
);

Enter fullscreen mode Exit fullscreen mode

In the above example the category table is the one and the product table is the many, categoryID in product table is the foreign key that references the primary key categoryID in categories table.

This creates a one-to-many relationship, where each category can have multiple products, but each product can only belong to one category.

The primary key in the "orderDetails" table
A primary key is a column or a set of columns that uniquely identifies each row in a table. In this case, the combination of the "orderID" and "productID" columns together, is used to uniquely identify each row in the "orderDetails" table. This means that there cannot be two rows with the same values for both "orderID" and "productID" columns.

It is called a composite primary key, it is used when we have more than one column that needed to be unique in the table.
The primary key is used to enforce the integrity of the data in the table and to create relationships between tables.

Side Note: Enforcing the integrity of the data in a table
Enforcing the integrity of the data in a table means making sure that the data in the table is accurate, consistent and valid. This is done by setting rules and constraints on the table, such as the primary key, foreign key, unique and not null constraints, etc.

For example, in the table "orders" if we enforce the integrity of the data by setting the customerID as a foreign key that references the primary key customerID in the customers table, this will ensure that every customer ID in the order table must exist in the customer table, so this will prevent any invalid customer ID from being entered in the orders table.

Another example, in the table "orderDetails" if we enforce the integrity of the data by setting the composite primary key ( orderID, productID) this will ensure that every order and product combination is unique, so this will prevent any duplication of order and product in the orderDetails table.

By enforcing these constraints and rules, the database management system can prevent any accidental or intentional errors from occurring, such as duplicate data, missing data, or data that does not conform to the rules. Thus, it guarantees the integrity of the data in the table.

Data can be inserted into the "customers", "categories", "products", "orders", and "orderDetails" tables:

INSERT INTO customers (firstName, lastName, email, password) 
VALUES ('John', 'Doe', 'johndoe@email.com', 'password123');

INSERT INTO categories (name) 
VALUES ('Electronics');

INSERT INTO products (name, price, categoryID) 
VALUES ('Laptop', 999.99, 1);

INSERT INTO orders (customerID, orderDate) 
VALUES (1, '2022-01-01');

INSERT INTO orderDetails (orderID, productID, quantity) 
VALUES (1, 1, 2);

Enter fullscreen mode Exit fullscreen mode

The first query inserts a new row into the "customers" table with the first name "John", last name "Doe", email "johndoe@email.com", and password "password123".

The second query inserts a new row into the "categories" table with the name "Electronics".

The third query inserts a new row into the "products" table with the name "Laptop", price "999.99", and category ID "1".

The fourth query inserts a new row into the "orders" table with the customer ID "1" and order date "2022-01-01".

The fifth query inserts a new row into the "orderDetails" table with the order ID "1", product ID "1", and quantity "2".

Keep in mind that the the values of foreign keys should match the existing values in the referenced table, otherwise it will cause an error.

Retrieve Data
So, when you want to retrieve the data from the "customers" table and the "orders" table together, you can use the join statement on the "customerID" column.

SELECT customers.firstName, customers.lastName, orders.orderDate
FROM customers
JOIN orders
ON customers.customerID = orders.customerID;
Enter fullscreen mode Exit fullscreen mode

This query will return the first name, last name, and order date of customers, and it will join the customers table and orders table based on the customerID column.

You can also use other clauses such as WHERE, GROUP BY, HAVING, ORDER BY, LIMIT to retrieve the data in a specific way.

This relationship is important because it allows you to link specific orders to specific customers and retrieve the customer's information when you need it.

Okay, but what is the relationship between "products" table, "orders" table, and "orderDetails" table?

The relationship between the "products" table, "orders" table, and "orderDetails" table is a many-to-many relationship.

This is because, for each order, there can be multiple products included (many order details), and each product can be included in multiple orders.

To handle this relationship, we use a bridge table called "orderDetails" that has a composite primary key (orderID, productID) that references the primary keys of "orders" and "products" tables. Each row in the "orderDetails" table represents a specific product that is included in a specific order.

So, when you want to retrieve the data from the "products" table, "orders" table and "orderDetails" table together, you can use the join statement on the "orderDetails" table, as I mentioned before:

SELECT orderDetails.orderID, products.name, products.price, orderDetails.quantity 
FROM orderDetails
JOIN products
ON orderDetails.productID = products.productID;

Enter fullscreen mode Exit fullscreen mode

Creating a many-to-many relationship in MySQL is done by using a bridge table (also known as a junction table or join table) that has a composite primary key that references the primary keys of the two tables that you want to connect.

Here is an example of how to create a many-to-many relationship between a "products" table and a "orders" table using a "orderDetails" table:

CREATE TABLE orderDetails (
  orderID INT NOT NULL,
  productID INT NOT NULL,
  quantity INT NOT NULL,
  PRIMARY KEY (orderID, productID),
  FOREIGN KEY (orderID) REFERENCES orders(orderID),
  FOREIGN KEY (productID) REFERENCES products(productID)
);
Enter fullscreen mode Exit fullscreen mode

In this example, the "orderDetails" table has a composite primary key (orderID, productID) that references the primary keys of "orders" and "products" tables.
This composite primary key ensures that each combination of orderID and productID is unique in the table.

The foreign keys in the "orderDetails" table, orderID and productID are used to reference the primary keys of the "orders" and "products" tables, respectively. This creates the many-to-many relationship between the "products" and "orders" tables.

Top comments (0)