MySQL: Joining three tables

Profile picture for user arilio666

Today in this article we will be looking at the topic of joining three tables and how we can do that with real-time examples. Now we know joining is the process of sticking up two tables with one another based on the common columns present across.

So enough theory lets us dive into the real-time example.

Today we will be using the orders, customers, order statuses tables for performing joining operations.

So here is what we are gonna do:

  • We are gonna get the first name and last name from the customer table and order id and dates from the orders table based on the common column between these and then join the order status with them to get the shipping details.
  • So in the simple term, we are gonna get the shipment status of customers along with their order id and dates of order.
  • As you can see all of these are in separate tables.

Getting The Shipping Status Of Every Customers Along With Order Id And Dates:

select * from orders o join customers c ON o.customer_id = c.customer_id 
join order_statuses os ON o.status = os.order_status_id;

  • So from the query, we can see that we have joined 3 tables based on customer id for the table customers and orders and also we have aliased every table to make it look compact.
  • order_statuses table based on status and order status id from the orders table.
  • So the goal is to match the status id from order_statuses with status from orders to get the shipping status in words for more understanding.

So the table displayed here looks clumsy we can select the relevant tables now and display them for easy understanding.

select o.order_id, o.order_date, c.first_name, c.last_name, os.name AS status 
from orders o join customers c ON o.customer_id = c.customer_id 
join order_statuses os ON o.status = os.order_status_id;

  • So from here, we have the order_id from o/orders aliased table, date, customer's name from c/customers aliased table, name column from order_statuses table, and aliased the column as status for better understanding.
  • The rest of the query is the same.
  • So here we are getting the compact result of a 3 joined table of what we need.
Tags