Can we include a JavaScript Array within a SQL query?

Can a javascript array be used in an SQL query?

I need to pass studentsId as a parameter in the second query.

db.query('SELECT users.* FROM users JOIN classes ON users.class_id=classes.id WHERE classes.id ="' + req.body.classSelect + '" ', function (err, rows) {

    // Store all user ids obtained from the first query
    var studentsId = [];
    for (var i = 0; i < rows.length; i++) {
        studentsId.push(rows[i].id);
    }
    console.log(studentsId);

    // Use studentsId in this query
    db.query("SELECT users.id, users.first_name, users.last_name,attendances.type_id,attendances.attendance_timestamp FROM users JOIN attendances ON attendances.user_id = users.id WHERE attendance_timestamp BETWEEN '2016-01-01' AND '2016-12-31' AND user_id IN ('"+ studentsId +"') ", function (err, result) {
        if (err) {
            throw err;
        }
        console.log(result);
    });
});

Answer №1

A slight modification is required from the way you are currently doing it.

First, adjust

studentsId.push(rows[i].id);

to be

studentsId.push('"' + rows[i].id + '"');

After that, update this line

db.query("SELECT users.id, users.first_name, users.last_name,
   attendances.type_id,attendances.attendance_timestamp FROM users 
   JOIN attendances ON attendances.user_id = users.id WHERE 
   attendance_timestamp BETWEEN '2016-01-01' AND '2016-12-31' 
   AND user_id IN ('"+ studentsId +"') ", function (err, result) {

to read like this

db.query("SELECT users.id, users.first_name, users.last_name,
   attendances.type_id, attendances.attendance_timestamp FROM users 
   JOIN attendances ON attendances.user_id = users.id WHERE
   attendance_timestamp BETWEEN '2016-01-01' AND '2016-12-31' 
   AND user_id IN (' + studentsId.join(',') + ') ", function (err, result) {

Once these adjustments are made, your code should function as intended.

The initial alteration simply surrounds the ID's with quotes, which may not be necessary for numeric IDs.

The second change concatenates the ID's together with commas for use in the query.

Answer №2

To optimize the query, consider merging the JOIN with attendances into the initial query rather than executing it separately.

db.query('SELECT users.* FROM users JOIN classes ON users.class_id=classes.id join attendances ON attendances.user_id = users.id WHERE classes.id ="' + req.body.classSelect + '" AND attendance_timestamp BETWEEN "2016-01-01" AND "2016-12-31" ', function (err, rows) {

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve a specific JSON object from an array of JSON objects by applying a condition with Restangular

How can I efficiently retrieve a specific playlist with user_id == 1 from a json api (playlists.json) without having to loop through all playlists? This is what I have tried so far: var playlists = Restangular.all('playlists'); playlists.getLi ...

Tips for adjusting the text color of input fields while scrolling down

I am currently working on my website which features a search box at the top of every page in white color. I am interested in changing the color of the search box to match the background color of each individual page. Each page has its own unique background ...

Utilizing the WHEN statement in a SELECT query for conditional counting

Looking for advice. I need to create a select statement that combines values from multiple columns. Specifically, I have a column called dtmStartProcess (which contains dates) and intProcessAfterDays (which contains numbers). I am trying to retrieve the ...

The three.js plugin is not loading in tern.js

Issue I am currently in the process of developing a 3D web application using three.js. For my development environment, I have opted to use neovim and YouCompleteMe for code completion. To enable JavaScript completion, I have installed tern and created a ...

I'm wondering why one of the queries in my sql/mariadb database is running so much slower than the other. The one

REMOVE FROM search WHERE sequence_id IN (34546); Affected records: 0 Duration: 0,001s GET sequence_id FROM sequences WHERE sequence_status = 1; All good Duration: 0,001s REMOVE FROM search WHERE sequence_id IN (GET sequence_id FROM sequence ...

Getting console data in AngularJS can be achieved by using the console.log()

This log in the console is functioning correctly. Is there a way to retrieve this information for the HTML? ProductController.js $scope.selectedProduct = function(product) { console.log(product.post_title); console.log(product.ID); console.l ...

Difficulty encountered when attempting to generate a Firestore document with the Firebase ID of a user

I am in the process of building a web application using Vue.js + Firebase. Currently, I am working on implementing a sign-up feature for the project. The sign-up feature utilizes a Firebase auth function and it is functioning correctly. However, I also ne ...

A guide to implementing infinite scrolling with vue-infinite-loading in Nuxt.js (Vue.js)

Currently, I am working on developing a web application using Nuxt.js (Vue.js). Initially, to set up the project, I used the command: vue init nuxt/express MyProject ~page/help.vue <template> <div> <p v-for="item in list"> ...

Display a pop-up upon clicking a button

I've created a custom popup form using Flodesk and added the corresponding Javascript Snippet to my website just before the closing head tag. <script> (function(w, d, t, h, s, n) { w.FlodeskObject = n; var fn = function() { (w[n] ...

Ways to cease a setInterval after a specified duration or a specific number of iterations

I have successfully implemented a jQuery code for creating a loop of "changing words" by referring to the solution provided in this Stack Overflow answer: jQuery: Find word and change every few seconds My question is, how can I stop this loop after a cert ...

What is the best way to save information from an ng-repeat loop into a variable before sending it to an API?

My goal is to store the selected value from ng-repeat in UI (user selection from dropdown) and assign it to a variable. function saveSelection() { console.log('inside function') var postToDatabase = []; vm.newApplicant.values ...

Can a JavaScript nested function be called like new fun1().fun2().fun3()?

This function is the original one that I have created function fun1(){ this.fun2 = function(){ this.fun3 = function(){ } } } When I execute the function like this new fun1().fun2() it works perfectly well. However, if I ...

Is nesting directives possible within AngularJS?

Having trouble creating a Directive that includes another directive from the AngularJS UI. Check out my html: <div class="col-md-12" ng-show="continent == '2'"> <my-rating></my-rating> </div> Here is the directiv ...

What is the correct way to incorporate a for loop within a script tag in EJS?

When attempting to create a chart using chart.js, I encountered an issue. In order to retrieve my data, I attempted to use ejs tags. For example, within the ejs input HTML below, everything worked smoothly. <p>date: <%= today %></p> ...

Creating a query in Python using the 'like' operator with the MySQL connector

Looking for guidance on writing a query using the mysql connector and python with like to avoid sql injections. Using an ORM is not an option for me at the moment. param = 'bob' select_query = mysql_conn.query_db("select * from table_one where c ...

Is there a way to execute the href="#var=something" before the onclick function is triggered in JavaScript?

Presently, I am utilizing the following JavaScript code to switch an image on an ASPX page in ASP.NET C#. <script language="JavaScript" type="text/javascript"> var updateImageWhenHashChanges = function() { theImag ...

Error: Attempting to access the 'street' property of an undefined value

My application loads a JSONPlaceholder data list of users, and I am attempting to enable editing of this data. However, I encounter an error: TypeError: Cannot read property 'street' of undefined Is there anyone who can provide assistance? c ...

What are some common applications of the QMap datatype in QML?

Let's say I have a simple QMap declared and initialized with values inside C++ and properly exposed to QML. C++ QMap<QString, QMap<QString, QString>> airflow_buttons_; //simple getter [[nodiscard]] QMap<QString, QMap<QString, QStr ...

Obtaining a key from a Firebase query using JavaScript

Is there a way to retrieve the key where UID is equal to: firebase.auth().currentUser.uid? I need to be able to update this information whenever the user inputs new data. Also, how can I update the information effectively? I have tried using orderByChild ...

Adding new element to 2D array

I'm currently facing an issue while attempting to insert strings into a 2D array using Google Apps Script. The behavior I'm encountering is quite peculiar and I'm struggling to comprehend it fully. Below is a simplified version of the code t ...