Lecture # 6
Node.js MySQL
By Dr. Sidra Sultana
1 Dr. Sidra Sultana
Node.js MySQL
Node.js can be used in database applications.
MySQL Database
Install MySQL Driver
Once you have MySQL up and running on your computer, you
can access it by using Node.js.
To access a MySQL database with Node.js, you need a MySQL
driver.
To download and install the "mysql" module, open the
Command Terminal and execute the following:
C:\Users\Your Name>npm install mysql
Node.js can use this module to manipulate the MySQL database:
var mysql = require('mysql');
2 Dr. Sidra Sultana
Create Connection
Start by creating a connection to the database.
Use the username and password from your MySQL database.
demo_db_connection.js
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
Save the code above in a file called "demo_db_connection.js" and run the file:
Run "demo_db_connection.js"
C:\Users\Your Name>node demo_db_connection.js
Connected!
3 Dr. Sidra Sultana
Query a Database
Use SQL statements to read from (or write to) a MySQL database.
The connection object created in the example above, has a method
for querying the database:
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Result: " + result);
});
});
The query method takes an sql statements as a parameter and
returns the result.
4 Dr. Sidra Sultana
Creating a Database
To create a database in MySQL, use the "CREATE DATABASE" statement:
Example
Create a database named "mydb":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword"
});
con.connect(function(err) {
if (err) throw err;
console.log("! Connected");
con.query("CREATE DATABASE mydb", function (err, result) {
if (err) throw err;
console.log("Database created");
});
});
Save the code above in a file called "demo_create_db.js" and run the file:
Run "demo_create_db.js"
C:\Users\Your Name>node demo_create_db.js
Which will give you this result: Connected! Database created
5 Dr. Sidra Sultana
Creating a Table
To create a table in MySQL, use the "CREATE TABLE" statement.
Make sure you define the name of the database when you create the connection:
Example
Create a table named "customers":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
});
Save the code above in a file called "demo_create_table.js" and run the file:
Run "demo_create_table.js"
C:\Users\Your Name>node demo_create_table.js
Which will give you this result: Connected! Table created
6 Dr. Sidra Sultana
Primary Key
When creating a table, you should also create a column with a unique key for each record.
This can be done by defining a column as "INT AUTO_INCREMENT PRIMARY KEY" which will insert
a unique number for each record. Starting at 1, and increased by one for each record.
Example
Create primary key when creating the table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "CREATE TABLE customers (id INT AUTO_INCREMENT PRIMARY KEY, name
VARCHAR(255), address VARCHAR(255))";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table created");
});
}); 7 Dr. Sidra Sultana
Primary Key cont’d
If the table already exists, use the ALTER TABLE keyword:
Example
Create primary key on an existing table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "ALTER TABLE customers ADD COLUMN id INT AUTO_INCREMENT PRIMARY KEY";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table altered");
});
});
8 Dr. Sidra Sultana
Node.js MySQL Insert Into
Example
Insert a record in the "customers" table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ('Company
Inc', 'Highway 37')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted");
});
});
9 Dr. Sidra Sultana
Insert Multiple Records
To insert more than one record, make an array containing the values, and insert a question mark
in the sql, which will be replaced by the value array:
INSERT INTO customers (name, address) VALUES ?
Example
Fill the "customers" table with data:
var mysql = require('mysql');
var con = mysql.createConnection({
…
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
var sql = "INSERT INTO customers (name, address) VALUES ?";
var values = [
['John', 'Highway 71'],
['Ben', 'Park Lane 38'],
['Viola', 'Sideway 1633']
];
con.query(sql, [values], function (err, result) {
if (err) throw err;
console.log("Number of records inserted: " + result.affectedRows);
});
10 Dr. Sidra Sultana
});
The Result Object
When executing a query, a result object is returned.
The result object contains information about how the query affected the table.
The result object returned from the example above looks like this:
{
fieldCount: 0,
affectedRows: 3,
insertId: 0,
serverStatus: 2,
warningCount: 0,
message: '\'Records:3 Duplicated: 0 Warnings: 0',
protocol41: true,
changedRows: 0
}
The values of the properties can be displayed like this:
Example
Return the number of affected rows:
console.log(result.affectedRows)
Which will produce this result:
3
11 Dr. Sidra Sultana
Get Inserted ID
For tables with an auto increment id field, you can get the id of the row you just inserted by
asking the result object.
Note: To be able to get the inserted id, only one row can be inserted.
Example
Insert a record in the "customers" table, and return the ID:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "INSERT INTO customers (name, address) VALUES ('Michelle', 'Blue Village 1')";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("1 record inserted, ID: " + result.insertId);
});
});
12 Dr. Sidra Sultana
Node.js MySQL Select From
Selecting From a Table
To select data from a table in MySQL, use the "SELECT" statement.
Example
Select all records from the "customers" table, and display the result object:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
13 Dr. Sidra Sultana
Node.js MySQL Select From cont’d
SELECT * will return all columns
Save the code above in a file called "demo_db_select.js" and run the file:
Run "demo_db_select.js"
C:\Users\Your Name>node demo_db_select.js
Which will give you this result:
[
{ id: 1, name: 'John', address: 'Highway 71'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'},
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 9, name: 'Susan', address: 'One way 98'},
{ id: 10, name: 'Vicky', address: 'Yellow Garden 2'},
{ id: 11, name: 'Ben', address: 'Park Lane 38'},
{ id: 12, name: 'William', address: 'Central st 954'},
{ id: 13, name: 'Chuck', address: 'Main Road 989'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'}
]
14 Dr. Sidra Sultana
Selecting Columns
To select only some of the columns in a table, use the "SELECT" statement followed by the column
name.
Example
Select name and address from the "customers" table, and display the return object:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
15 Dr. Sidra Sultana
Selecting Columns cont’d
Save the code above in a file called "demo_db_select2.js" and run the file:
Run "demo_db_select2.js"
C:\Users\Your Name>node demo_db_select2.js
Which will give you this result:
[
{ name: 'John', address: 'Highway 71'},
{ name: 'Peter', address: 'Lowstreet 4'},
{ name: 'Amy', address: 'Apple st 652'},
{ name: 'Hannah', address: 'Mountain 21'},
{ name: 'Michael', address: 'Valley 345'},
{ name: 'Sandy', address: 'Ocean blvd 2'},
{ name: 'Betty', address: 'Green Grass 1'}
]
The Result Object
console.log(result[2].address);
Which will produce this result:
Apple st 652
16 Dr. Sidra Sultana
The Fields Object
The third parameter of the callback function is an array containing information about each field in
the result.
Example
Select all records from the "customers" table, and display the fields object:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT name, address FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(fields);
});
});
17 Dr. Sidra Sultana
The Fields Object cont’d
Which will give you this result:
[{
catalog: 'def',
db: 'mydb',
table: 'customers',
orgTable: 'customers',
name: 'name',
orgName: 'address',
charsetNr: 33,
length: 765,
type: 253,
flags: 0,
decimals: 0,
default: undefined,
zeroFill: false,
protocol41: true
}, {…}]
As you can see from the result of the example above, the fields object is an array containing
information about each field as an object.
To return e.g. the name of the second field, just refer to the second array item's name property:
console.log(fields[1].name);
18 Dr. Sidra Sultana
Node.js MySQL Where
Select With a Filter
When selecting records from a table, you can filter the selection by using the "WHERE" statement:
Example
Select record(s) with the address "Park Lane 38":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address = 'Park Lane 38'", function (err,
result) {
if (err) throw err;
console.log(result);
});
});
Which will give you this result:
[ { id: 11, name: 'Ben', address: 'Park Lane 38'}]
19 Dr. Sidra Sultana
Wildcard Characters
You can also select the records that starts, includes, or ends with a given letter or phrase.
Use the '%' wildcard to represent zero, one or multiple characters:
Example
Select records where the address starts with the letter 'S':
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers WHERE address LIKE 'S%'", function (err, result)
{
if (err) throw err;
console.log(result);
});
});
[ { id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'}]
20 Dr. Sidra Sultana
Escaping Query Values
When query values are variables provided by the user, you
should escape the values.
This is to prevent SQL injections, which is a common web
hacking technique to destroy or misuse your database.
The MySQL module has methods to escape query values:
Example
Escape query values by using the mysql.escape() method:
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ' +
mysql.escape(adr);
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
21 Dr. Sidra Sultana
Escaping Query Values cont’d
You can also use a ? as a placeholder for the values you want to escape.
In this case, the variable is sent as the second parameter in the query() method:
Example
Escape query values by using the placeholder ? method:
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE address = ?';
con.query(sql, [adr], function (err, result) {
if (err) throw err;
console.log(result);
});
If you have multiple placeholders, the array contains multiple values, in that order:
Example
Multiple placeholders:
var name = 'Amy';
var adr = 'Mountain 21';
var sql = 'SELECT * FROM customers WHERE name = ? OR address = ?';
con.query(sql, [name, adr], function (err, result) {
if (err) throw err;
console.log(result);
});
22 Dr. Sidra Sultana
Node.js MySQL Order By
Sort the Result
Use the ORDER BY statement to sort the result in ascending or descending order.
The ORDER BY keyword sorts the result ascending by default. To sort the result in descending
order, use the DESC keyword.
Example
Sort the result alphabetically by name:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers ORDER BY name", function (err, result) {
if (err) throw err;
console.log(result);
});
});
23 Dr. Sidra Sultana
Node.js MySQL Order By cont’d
Run example »
Save the code above in a file called "demo_db_orderby.js" and run the file:
Run "demo_db_orderby.js"
C:\Users\Your Name>node demo_db_orderby.js
Which will give you this result:
[
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 11, name: 'Ben', address: 'Park Lane 38'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'},
{ id: 13, name: 'Chuck', address: 'Main Road 989'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 1, name: 'John', address: 'Higheay 71'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 9, name: 'Susan', address: 'One way 98'},
{ id: 10, name: 'Vicky', address: 'Yellow Garden 2'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'},
{ id: 12, name: 'William', address: 'Central st 954'}
]
24 Dr. Sidra Sultana
Node.js MySQL Order By cont’d
ORDER BY DESC
Use the DESC keyword to sort the result in a descending order.
Example
Sort the result reverse alphabetically by name:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers ORDER BY name DESC", function (err, result) {
if (err) throw err;
console.log(result);
});
});
25 Dr. Sidra Sultana
Node.js MySQL Order By cont’d
Save the code above in a file called "demo_db_orderby_desc.js" and run the file:
Run "demo_db_orderby_desc.js"
C:\Users\Your Name>node demo_db_orderby_desc.js
Which will give you this result:
[
{ id: 12, name: 'William', address: 'Central st 954'},
{ id: 14, name: 'Viola', address: 'Sideway 1633'},
{ id: 10, name: 'Vicky', address: 'Yellow Garden 2'},
{ id: 9, name: 'Susan', address: 'One way 98'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 8, name: 'Richard', address: 'Sky st 331'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 1, name: 'John', address: 'Higheay 71'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 13, name: 'Chuck', address: 'Main Road 989'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'},
{ id: 11, name: 'Ben', address: 'Park Lane 38'},
{ id: 3, name: 'Amy', address: 'Apple st 652'}
]
26 Dr. Sidra Sultana
Node.js MySQL Delete
Delete Record
You can delete records from an existing table by using the "DELETE FROM" statement:
Example
Delete any record with the address "Mountain 21":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "DELETE FROM customers WHERE address = 'Mountain 21'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Number of records deleted: " + result.affectedRows);
});
});
Notice the WHERE clause in the DELETE syntax: The WHERE clause specifies which record or records
that should be deleted. If you omit the WHERE clause, all records will be deleted!
Which will give you this result:
Number of records deleted: 1
27 Dr. Sidra Sultana
The Result Object
When executing a query, a result object is returned.
The result object contains information about how the query affected the table.
The result object returned from the example above looks like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
The values of the properties can be displayed like this:
Example
Return the number of affected rows:
console.log(result.affectedRows)
Which will produce this result:
1
28 Dr. Sidra Sultana
Node.js MySQL Drop Table
Delete a Table: You can delete an existing table by using the "DROP TABLE" statement:
Example, Delete the table "customers":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "DROP TABLE customers";
con.query(sql, function (err, result) {
if (err) throw err;
console.log("Table deleted");
});
});
Which will give you this result:
Table deleted
29 Dr. Sidra Sultana
Drop Only if Exist
If the the table you want to delete is already deleted, or for any other reason does not exist, you can use
the IF EXISTS keyword to avoid getting an error.
Example
Delete the table "customers" if it exists:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "DROP TABLE IF EXISTS customers";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
30 Dr. Sidra Sultana
Drop Only if Exist cont’d
If the table exist, the result object will look like this:
{
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverstatus: 2,
warningCount: 0,
message: '',
protocol41: true,
changedRows: 0
}
If the table does not exist, the result object will look like this:
{
fieldCount: 0,
affectedRows: 0,
insertId: 0,
serverstatus: 2,
warningCount: 1,
message: '',
protocol41: true,
changedRows: 0
}
As 31you can see the only differnce is that the warningCount Dr.property is set to 1 if the table does not exist.
Sidra Sultana
Node.js MySQL Update
Example
Overwrite the address column from "Valley 345" to "Canyon 123":
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "UPDATE customers SET address = 'Canyon 123' WHERE address
= 'Valley 345'";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result.affectedRows + " record(s) updated");
});
});
32 Dr. Sidra Sultana
The Result Object
When executing a query, a result object is returned.
The result object contains information about how the query affected the table.
The result object returned from the example above looks like this:
{
fieldCount: 0,
affectedRows: 1,
insertId: 0,
serverStatus: 34,
warningCount: 0,
message: '(Rows matched: 1 Changed: 1 Warnings: 0',
protocol41: true,
changedRows: 1
}
The values of the properties can be displayed like this:
Example
Return the number of affected rows:
console.log(result.affectedRows)
Which will produce this result:
1
33 Dr. Sidra Sultana
Node.js MySQL Limit
Limit the Result
You can limit the number of records returned from the query, by using the "LIMIT"
statement:
Example
Select the 5 first records in the "customers" table:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers LIMIT 5";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
34 Dr. Sidra Sultana
});
Node.js MySQL Limit cont’d
Save the code above in a file called "demo_db_limit.js" and
run the file:
Run "demo_db_limit.js"
C:\Users\Your Name>node demo_db_limit.js
Which will give you this result:
[
{ id: 1, name: 'John', address: 'Highway 71'},
{ id: 2, name: 'Peter', address: 'Lowstreet 4'},
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'}
]
35 Dr. Sidra Sultana
Start From Another Position
If you want to return five records, starting from the third record, you can use the "OFFSET" keyword:
Example
Start from position 3, and return the next 5 records:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers LIMIT 5 OFFSET 2";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
36 Dr. Sidra Sultana
Start From Another Position cont’d
Note: "OFFSET 2", means starting from the third position, not the second!
Save the code above in a file called "demo_db_offset.js" and run the file:
Run "demo_db_offset.js"
C:\Users\Your Name>node demo_db_offset.js
Which will give you this result:
[
{ id: 3, name: 'Amy', address: 'Apple st 652'},
{ id: 4, name: 'Hannah', address: 'Mountain 21'},
{ id: 5, name: 'Michael', address: 'Valley 345'},
{ id: 6, name: 'Sandy', address: 'Ocean blvd 2'},
{ id: 7, name: 'Betty', address: 'Green Grass 1'}
]
37 Dr. Sidra Sultana
Shorter Syntax
You can also use write your SQL statement like this "LIMIT 2, 5" which returns the same as the offset example
above:
Example
Start from position 3, and return the next 5 records:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT * FROM customers LIMIT 2, 5";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
});
Note: The numbers are reversed: "LIMIT 2, 5" is the same as "LIMIT 5 OFFSET 2"
38 Dr. Sidra Sultana
Node.js MySQL Join
Join Two or More Tables
You can combine rows from two or more tables, based on a related column between
them, by using a JOIN statement.
Consider you have a "users" table and a "products" table:
users
[ { id: 1, name: 'John', favorite_product: 154},
{ id: 2, name: 'Peter', favorite_product: 154},
{ id: 3, name: 'Amy', favorite_product: 155},
{ id: 4, name: 'Hannah', favorite_product:},
{ id: 5, name: 'Michael', favorite_product:}]
products
[ { id: 154, name: 'Chocolate Heaven' },
{ id: 155, name: 'Tasty Lemons' },
{ id: 156, name: 'Vanilla Dreams' }]
These two tables can be combined by using users' favorite_product field and
products' id field.
39 Dr. Sidra Sultana
Node.js MySQL Join cont’d
Example
Select records with a match in both tables:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
var sql = "SELECT users.name AS user, products.name AS favorite
FROM users JOIN products ON users.favorite_product = products.id";
con.query(sql, function (err, result) {
if (err) throw err;
console.log(result);
});
40 Dr. Sidra Sultana
});
Node.js MySQL Join cont’d
Note: You can use INNER JOIN instead of JOIN. They will both give
you the same result.
Save the code above in a file called "demo_db_join.js" and run the file:
Run "demo_db_join.js"
C:\Users\Your Name>node demo_db_join.js
Which will give you this result:
[
{ user: 'John', favorite: 'Chocolate Heaven' },
{ user: 'Peter', favorite: 'Chocolate Heaven' },
{ user: 'Amy', favorite: 'Tasty Lemons' }
]
As you can see from the result above, only the records with a match in
both tables are returned.
41 Dr. Sidra Sultana
Left Join
If you want to return all users, no matter if they have a favorite product or not, use
the LEFT JOIN statement:
Example
Select all users and their favorite product:
SELECT users.name AS user,
products.name AS favorite
FROM users
LEFT JOIN products ON users.favorite_product = products.id
Which will give you this result:
[
{ user: 'John', favorite: 'Chocolate Heaven' },
{ user: 'Peter', favorite: 'Chocolate Heaven' },
{ user: 'Amy', favorite: 'Tasty Lemons' },
{ user: 'Hannah', favorite: null },
{ user: 'Michael', favorite: null }
]
42 Dr. Sidra Sultana
Right Join
If you want to return all products, and the users who have them as their favorite, even if
no user have them as their favorite, use the RIGHT JOIN statement:
Example
Select all products and the user who have them as their favorite:
SELECT users.name AS user,
products.name AS favorite
FROM users
RIGHT JOIN products ON users.favorite_product = products.id
Which will give you this result:
[
{ user: 'John', favorite: 'Chocolate Heaven' },
{ user: 'Peter', favorite: 'Chocolate Heaven' },
{ user: 'Amy', favorite: 'Tasty Lemons' },
{ user: null, favorite: 'Vanilla Dreams' }
]
Note: Hannah and Michael, who have no favorite product, are not included in the result.
43 Dr. Sidra Sultana
Any Query?
44 Dr. Sidra Sultana
Thanks
45 Dr. Sidra Sultana