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:

CopiedCopy Code
npm install mysql
				

INTERSECT() Function:

INTERSECT() is used to return only the common rows from two or more tables.

We have to note that

  1. Column names may not be same but they are in same order with respect to datatypes.
  2. Total number of columns while selecting the columns with INTERSECT must be same.
Steps for Node.js script:

Now let's see steps

  1. First start your XAMPP Server (Both Apache and MySQL).
  2. Open Notepad or any text-editor and write the Node.js script
  3. In that script, first we have to load the mysql package using the below syntax
  4. var mysql_package = require('mysql');
  5. Create the connection using the server,username and password.
  6. CopiedCopy Code
    
    var connection_data = mysql_package.createConnection({
      host: "localhost",
      user: "root",
      password: "",
      database:"database_name"
    });
    
  7. Write the sql query that uses INTERSECT
  8. CopiedCopy Code
    
    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);
      });
    });
    
  9. Now type the following command in your command prompt to run the script.
  10. node file_name.js

Consider the village1 table with the following records:

alt=

Consider the village2 table with the following records:

alt=

INTERSECT Example 1:-

Let's select all the columns from the tables - village1 and village2 and perform intersection operation.

CopiedCopy Code

// 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:

CopiedCopy Code

[]

So, we can see that there is no common row among two tables. Hence, empty is returned.

Summary

In this post, we seen how to use mysql INTERSECT() function in Node.js Script with example.