Introduction
Joining multiple tables helps you combine related information from different places into one view.
SELECT columns FROM table1 JOIN table2 ON table1.column = table2.column JOIN table3 ON table2.column = table3.column;
SELECT orders.id, customers.name FROM orders JOIN customers ON orders.customer_id = customers.id;
SELECT orders.id, customers.name, products.name FROM orders JOIN customers ON orders.customer_id = customers.id JOIN products ON orders.product_id = products.id;
CREATE TABLE customers (id INT, name VARCHAR(20)); CREATE TABLE orders (id INT, customer_id INT, product_id INT); CREATE TABLE products (id INT, name VARCHAR(20)); INSERT INTO customers VALUES (1, 'Alice'), (2, 'Bob'); INSERT INTO products VALUES (10, 'Pen'), (20, 'Notebook'); INSERT INTO orders VALUES (100, 1, 10), (101, 2, 20); SELECT orders.id AS order_id, customers.name AS customer_name, products.name AS product_name FROM orders JOIN customers ON orders.customer_id = customers.id JOIN products ON orders.product_id = products.id;
JOIN with multiple tables in MySQL?employees and departments on the column department_id?JOIN departments ON employees.department_id = departments.department_id.students(id, name, class_id)classes(id, class_name)SELECT students.name, classes.class_name FROM students JOIN classes ON students.class_id = classes.id WHERE classes.class_name = 'Math';
class_id and id. The WHERE clause filters only classes named 'Math'.orders and customers:SELECT orders.id, customers.name FROM orders JOIN customers WHERE orders.customer_id = customers.id;
products(id, name, category_id)categories(id, category_name)sales(product_id, quantity)Pass the test and this pattern moves unknown