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
✅ 2. Connect to MySQL Database
✅ 3. Sample Tables
users Table
| id | name | |
|---|---|---|
| 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:
✅ 5. LEFT JOIN
Fetch all users, including those without orders:
-
Users with no orders will have
NULLfororders.productandorders.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.
