Languages
[Edit]
EN

Node.js - MySQL Inner Join

0 points
Created by:
Teilsa
1255

In this article, we would like to show you how to use MySQL INNER JOIN in Node.js.

Note: at the end of this article you can find database preparation SQL queries, you will also find an example of a more parameterized query there.

const mysql = require('mysql');

const connection = mysql.createConnection({        // gets connection with database
    host: 'localhost', // '127.0.0.1'
    user: 'root',
    password: 'password',
    database: 'my_database',
});

connection.connect((error) => {
    if (error) throw error;
    const query = 'SELECT * ' + 
                  'FROM `users` ' +
                  'JOIN `departments` ON `departments`.`id` = `users`.`department_id`';

    connection.query(query, (error, result) => {   // sends queries
        connection.end();                          // closes connection
        if (error) throw error;
        console.log(result);
    });
});
Tables in the database
Tables in the database

Output:

Result of the above JOIN query - HeidiSQL
Result of the above JOIN query - HeidiSQL

Database preparation

create_tables.sql file:

CREATE TABLE `departments` (
	`id` INT(10) UNSIGNED NOT NULL,
	`department_name` VARCHAR(50) NOT NULL,
	`location` VARCHAR(50) NULL,
	PRIMARY KEY (`id`)
);

CREATE TABLE `users` (
	`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
	`name` VARCHAR(50) NOT NULL,
	`surname` VARCHAR(50) NOT NULL,
	`department_id` INT(10) UNSIGNED,
	PRIMARY KEY (`id`),
	FOREIGN KEY (`department_id`) REFERENCES `departments` (`id`)
)

insert_data.sql file:

INSERT INTO `departments`
	(`id`, `department_name`, `location`)
VALUES
	(1, 'Sales', 'New York'),
	(2, 'Finance', NULL),
	(3, 'HR', 'Atlanta'),
	(4, 'Purchase', 'New Orlean'),
	(5, 'Operations', 'Boston');

INSERT INTO `users`
	( `name`, `surname`, `department_id`)
VALUES
	('John', 'Stewart', 1),
	('Chris', 'Brown', 2),
	('Kate', 'Lewis', 3),
	('Ailisa', 'Gomez', NULL),
	('Gwendolyn', 'James', 2),
	('Simon', 'Collins', 4),
	('Taylor', 'Martin', 2),
	('Andrew', 'Thompson', NULL);

More parameterized query

// ...
connection.connect(error => {
    if (error) throw error;
    const query = `SELECT * 
                   FROM ??
                   JOIN ?? ON ??.?? = ??.??`;
    const values = [
        'users',                 // SELECT *
        'departments',           // FROM `users`
        'departments',           // JOIN `departments` 
        'id',                    // ON departments.id = users.department_id
        'users',
        'department_id',
    ];

    connection.query(query, values, (error, result) => {  // sends queries
        connection.end();                                 // closes connection
        if (error) throw error;
        console.log(result);
    });
});

The names of columns and tables can be placed in the query by a double question mark ??.

Another parameterized solution: 

// ...
connection.connect((error) => {
    if (error) throw error;
    const query = `SELECT * FROM ?? AS A
                   JOIN ?? AS B ON A.?? = B.??`;
    const values = [
        'users',              // SELECT * FROM `users` AS A
        'departments',        // JOIN `departments` AS B ON B.id = A.department_id
        'users',
        'department_id',
    ];

    connection.query(query, values, (error, result) => {  // sends queries
        connection.end();                                // closes connection
        if (error) throw error;
        console.log(result);
    });
});
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - MySQL

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join