
Mysql Join in NodeJs
Using JOINs in MySQL with Node.js allows you to combine data from multiple tables β super useful for building real-world apps like blogs, e-commerce, and dashboards.
Let me show you how itβs done π
β Step 1: Setup (Install MySQL Package)
npm install mysql const mysql = require('mysql');const connection = mysql.createConnection({ host: 'localhost', user: 'root', password: '', database: 'myDatabase'});connection.connect((err) => { if (err) throw err; console.log('Connected to MySQL!'); const sql = ` SELECT users.name, orders.product FROM users JOIN orders ON users.id = orders.user_id `; connection.query(sql, (err, results) => { if (err) throw err; console.log('JOIN Results:'); console.table(results); connection.end(); });});
π§ Types of JOINs
JOIN Type | Description |
---|---|
INNER JOIN | Only matching records in both tables |
LEFT JOIN | All from left table + matches from right |
RIGHT JOIN | All from right table + matches from left |
FULL JOIN | All records (not supported directly in MySQL) |
π Tip: Alias & Format
SELECT u.name AS userName, o.productFROM users uJOIN orders o ON u.id = o.user_id