What is the best way to choose a random ID from a table within specified time intervals in MySQL?

I need to retrieve a random ID from the table nodes within the last 15 seconds.

I attempted the following code, but it produced a lengthy output:

    const mysql = require('mysql');
    
    const connection = mysql.createConnection({
      host: 'localhost',
      user: 'root',
      password: 'password',
      database: 'DAGtest3'
    });
    
    connection.connect((err) => {
      if (err) throw err;
      console.log('Database Connected!');
    });
    
    var b = connection.query("SELECT t.`id` FROM `nodes` AS t 
           INNER JOIN (SELECT ROUND( RAND() * (SELECT MAX(id) FROM `nodes` )) AS id ) AS x 
            WHERE t.id >= x.id AND created_at < DATE_SUB(NOW(), INTERVAL 15 SECOND) LIMIT 1");
    console.log(b);

output

Query // Output details removed for brevity

Any suggestions on how to resolve this issue?

Answer №1

In order to retrieve the error and result, it is essential to utilize the callback function.

Answer №2

It appears that the ROUND function in your SQL query is returning a decimal value. According to https://www.w3schools.com/SQL/func_sqlserver_round.asp, you should use an integer as the id. To resolve this issue, consider using either the FLOOR or CEILING SQL function instead.

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

Is there a way to unshackle myself from the promise chain in Express and trigger an error ahead of time

Upon examining my request handler, it appears as follows: router.post('/', function(req,res) { var screencast; var channel; youtube.get(req.body.videoId).then(function(data) { screencast = data.screencast; channel = data.channel; ...

Switching camera view on mouse click with three.js

I am new to three.js and apologize if my question is a bit complex. I have set up my scene in three.js but now I want the camera's position to smoothly transition from point A to point B (which I will specify in my code). I plan on using Tween.js to ...

Experimenting with the randomization of the insertion location for a name within a table using PHP and SQL

I have a task where I need to randomize elements within an array that contains column names, and then use these randomized column names to insert data into a table. However, the current code I'm using is causing an Internal Server Error. Here's ...

Ensuring that jQuery(document).ready(function() contains the appropriate content

Recently, I've been attempting to integrate a javascript gallery into my WordPress site. However, I'm encountering some confusion regarding what needs to be included in the .ready(function) to successfully run the gallery. The original jQuery fun ...

Guide on submitting a get form and retrieving the information

Currently, I am employed as a penetration tester for a company. While conducting an analysis of their website, I discovered a vulnerability where CSRF tokens are generated via a GET request to the page localhost/csrf-token and then provided in plaintext fo ...

Encountering a problem when attempting to send a JSON object with the BeanShell PreProcessor

I need to send a JSON Object to the HTTP Request body in JMeter using the BeanShell PreProcessor. The JSON object is modeled using java code with some business logic. I have created a BeanShell PreProcessor and written the java code below, import org.json ...

The footer is now accompanied by the <v-navigation-drawer> on the side

I am looking for a way to dynamically adjust the height value of a style applied to an element based on certain conditions. Specifically, when scrolling to the bottom, I want the height to be 77.5%, when the footer is not visible at all, it should be 100%, ...

What causes the first button to be clicked and the form to be submitted when the enter key is pressed within a text

Start by opening the javascript console, then place your cursor in the text box and hit enter. What is the reason for the function "baz" being called? How can this behavior be prevented? function foo() { console.log('foo'); } function bar() ...

Struggling with passing attributes to an AngularJS directive? You might be encountering the frustrating issue of receiving undefined values for

Currently, I am working on a directive that has four parameters being passed to it, all of which are bound to the directive scope. The problem I am facing is that despite the data existing and being loaded, the directive is receiving all values as undefin ...

Are there any potential risks of SQL Injection in this code? What steps can be taken to enhance its security?

I find myself in a position where I am assisting a friend with a project that involves cybersecurity. While I admit that I am not well-versed in penetration testing, my friend has tasked me with identifying potential security flaws in his program. Upon re ...

Query: What is the best method for calculating the distance between various sets of latitude and longitude coordinates?

Exploring the idea of creating a LAMP web application that allows users to input their location. Considering integrating Google Map API to convert their locations into lat/long coordinates. Assuming every user has this information, I am looking for guidanc ...

The data retrieved from the $.ajax() request in Vue.js is not properly syncing with the table

After setting up an $.ajax() function and ensuring the data binding is correctly configured, I expected the data to append to a table on page load without any issues. However, the data is not appearing as expected. Is there something that I might be overlo ...

Executing `removeChild` within a timeout during page load does not yield the expected results

I have an HTML div that is designed to contain dynamically generated children. These children are meant to be removed from the list after a specific amount of time (e.g. 1000 ms). Although some people have experienced scope issues with timeout functions, ...

Is there a way to overlay a div on a particular line within a p element?

Within this paragraph lies a collection of text encapsulated by a < p > tag. When this content is displayed on the page, it spans across 5 lines. My objective is to creatively style and position a < div > tag in order to highlight a specific li ...

Error: The promise was not caught due to a network issue, resulting in a creation error

I'm trying to use Axios for API communication and I keep encountering this error. Despite researching online and attempting various solutions, I am still unable to resolve the problem. Can someone please assist me? All I want is to be able to click on ...

Dynamically Loading CSS files in a JQuery plugin using a Conditional Test

I'm trying to figure out the optimal way to dynamically load certain files based on specific conditions. Currently, I am loading three CSS files and two javascript files like this: <link href="core.min.css" rel="stylesheet" type="text/css"> & ...

"Ensure div remains at the bottom of the page even while

In order to implement a feature where the menu sticks to the top when scrolling down, you can use the following JS code. You can view a live example of this functionality on this Plunker by widening the preview window to see the columns side by side. wi ...

Issue with the status of a vue data object within a component

While working on updating my original Vue project, I encountered an error with the data object sports_feeds_boxscores_*. The website features three tabs that display scores for the major sports leagues. I am currently in the process of adding player stats ...

Ways to verify if a component triggers an event in VueJS

I am currently working with two components within my application. The Child component emits an 'input' event whenever its value is changed, and the Parent component utilizes v-model to receive this updated value. In order to ensure that the funct ...

What is the proper way to detach an event listener from a class?

I am facing a challenge when trying to remove an event listener. After running the script, I receive an error message stating that changeGirl.off("click") is not a function. Despite this issue, everything else within the code is working perfectly fine. Any ...