Node.js - MySQL Intersect
In this post, we will discuss how to perform INTERSECT operation on MySQL Data in XAMPP Server using Node.js script.
It is important to install mysql package in node.js.
Command to install the mysql package:
Copied
npm install mysql
INTERSECT() Function:
INTERSECT() is used to return only the common rows from two or more tables.
We have to note that
- Column names may not be same but they are in same order with respect to datatypes.
- Total number of columns while selecting the columns with INTERSECT must be same.
Now let's see steps
- First start your XAMPP Server (Both Apache and MySQL).
- Open Notepad or any text-editor and write the Node.js script
- In that script, first we have to load the mysql package using the below syntax var mysql_package = require('mysql');
- Create the connection using the server,username and password.
- Write the sql query that uses INTERSECT
- Now type the following command in your command prompt to run the script. node file_name.js
Copied
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"database_name"
});
Copied
connection_data.connect(function(error) {
connection_data.query("SELECT columns from from table_name1 INTERSECT
SELECT columns from from table_name2", function (error, result) {
console.log(result);
});
});
Consider the village1 table with the following records:
Consider the village2 table with the following records:
INTERSECT Example 1:-
Let's select all the columns from the tables - village1 and village2 and perform intersection operation.
Copied
// Load the mysql package
var mysql_package = require('mysql');
// Create the connection using the server,username and password.
//In my scenario - server is the localhost,
//username is root,
//password is empty.
//database is facility
var connection_data = mysql_package.createConnection({
host: "localhost",
user: "root",
password: "",
database:"facility"
});
connection_data.connect(function(error) {
// Write SQL query to return the rows by performing intersect
//on two tables village1 and village2.
connection_data.query("SELECT name,district from village1 INTERSECT select name,
district from village2", function (error, result) {
//Display the records one by one
console.log(result);
});
});
Output:
Copied
[]
So, we can see that there is no common row among two tables. Hence, empty is returned.
SummaryIn this post, we seen how to use mysql INTERSECT() function in Node.js Script with example.