EN
Node.js - MySQL GROUP BY
0
points
In this article, we would like to show you how to use MySQLΒ GROUP BYΒ in Node.js.
Note:Β at the end of this article you can find database preparation SQL queries.
const mysql = require('mysql');
const connection = mysql.createConnection({ // gets connection with database
host: 'localhost', // '127.0.0.1'
user: 'root',
password: '',
database: 'test',
});
connection.connect(error => {
if (error) throw error;
const query ='SELECT COUNT(`id`) AS `number of users`, `country` ' +
'FROM `users` ' +
'GROUP BY `country` ' +
'ORDER BY COUNT(`id`) DESC;';
connection.query(query, (error, result) => { // sends queries
connection.end(); // closes connection
if (error) throw error;
console.table(result);
});
});
Result:Β
βββββββββββ¬ββββββββββββββββββ¬ββββββββββββ
β (index) β number of users β country β
βββββββββββΌββββββββββββββββββΌββββββββββββ€
β 0 β '3' β 'Spain' β
β 1 β '2' β 'Vietnam' β
β 2 β '1' β 'Italy' β
β 3 β '1' β 'Poland' β
βββββββββββ΄ββββββββββββββββββ΄ββββββββββββ
Database preparation
create_tables.sql
Β file:
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(100) NOT NULL,
`country` VARCHAR(15) NOT NULL,
PRIMARY KEY (`id`)
)
ENGINE=InnoDB;
insert_data.sql
Β file:
INSERT INTO `users`
(`name`, `country`)
VALUES
('Tom', 'Poland'),
('Chris', 'Spain'),
('Jack', 'Spain'),
('Kim', 'Vietnam'),
('Marco', 'Italy'),
('Kate', 'Spain'),
('Nam', 'Vietnam');