Node.js MySQL Join

🚀 Node.js MySQL – JOIN Queries

JOIN is used to combine rows from two or more tables based on a related column.

We’ll use mysql2 for all examples.


✅ 1. Install mysql2

npm install mysql2

✅ 2. Connect to MySQL Database


 


✅ 3. Sample Tables

users Table

id name email
1 John john@example.com
2 Alice alice@example.com

orders Table

id user_id product price
1 1 Laptop 1000
2 1 Mouse 20
3 2 Keyboard 50

✅ 4. INNER JOIN

Fetch users with their orders:


 

Output:

[
{ "id": 1, "name": "John", "product": "Laptop", "price": 1000 },
{ "id": 1, "name": "John", "product": "Mouse", "price": 20 },
{ "id": 2, "name": "Alice", "product": "Keyboard", "price": 50 }
]

✅ 5. LEFT JOIN

Fetch all users, including those without orders:


 

  • Users with no orders will have NULL for orders.product and orders.price.


✅ 6. RIGHT JOIN

Fetch all orders, including those without matching users:


 

  • Useful if orders may exist for deleted or missing users.


✅ 7. JOIN with WHERE and ORDER BY


 

  • Filters orders with price > 30

  • Sorts results by price descending


✅ 8. Using Async/Await

 


✅ 9. Best Practices

  • Use INNER JOIN to get only matching rows.

  • Use LEFT JOIN to include all rows from the left table.

  • Use prepared statements (?) for dynamic filters.

  • Combine with WHERE, ORDER BY, LIMIT for efficient queries.

  • Always alias columns if multiple tables have the same column names.

You may also like...