jeudi 7 janvier 2021

How to prevent Duplicate entry for inserting two unique random values in a single operation in MySQL?

I need to select two unique random id from table nodes and insert it in parent column in edges table for the same value of child column in the same table edges every 10 seconds. But problem is that they are sometimes duplicated (I mean the random selection id is the same for the same operation parent column) and I need them to be always different and unique, how could I avoid that, please?

The code:

var a = "INSERT INTO `edges` (`parent`, `child`) VALUES 
( (SELECT `id` FROM `nodes` WHERE created_at < DATE_SUB(NOW(), INTERVAL 10 SECOND) ORDER BY rand() LIMIT 1 ) , 
( SELECT `id` FROM `nodes` WHERE `sensorvalue` = ("4") ORDER BY id DESC LIMIT 1 ) ), 
( (SELECT `id` FROM `nodes` WHERE created_at < DATE_SUB(NOW(), INTERVAL 10 SECOND) ORDER BY rand() LIMIT 1 ) , 
( SELECT `id` FROM `nodes` WHERE `sensorvalue` = ("4") ORDER BY id DESC LIMIT 1 ) )";

connection.query(a, (err, res) => {
   if(err) throw err;
   console.log("two edges inserted to previous data");
});

Sometimes it shows this error: Duplicate entry '7-29' for key 'edges.PRIMARY'

I have tried to do that as well:

var r = [];

r ="SELECT `id` FROM `nodes` WHERE created_at < DATE_SUB(NOW(), INTERVAL 10 SECOND) ORDER BY rand() LIMIT 2";

connection.query(r);

for (var i=0; i<2; i++) {
    var a = "INSERT INTO `edges` (`parent`, `child`) VALUES 
    ( (?) , 
    ( SELECT `id` FROM `nodes` WHERE `sensorvalue` = ("4") ORDER BY id DESC LIMIT 1 ) )";
    
    connection.query(a, r[i], (err, res) => {
       if(err) throw err;
       console.log("two edges inserted to previous data");
    });
}

but it shows the error: Incorrect integer value: 'S' for column 'parent' at row 1

My Tables:

CREATE TABLE nodes (
    id INTEGER NOT NULL AUTO_INCREMENT,
    sensorvalue VARCHAR(255) NOT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);
 
CREATE TABLE edges (
    parent INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
    child INTEGER NOT NULL REFERENCES nodes(id) ON UPDATE CASCADE ON DELETE CASCADE,
    PRIMARY KEY (parent, child)
);
 
CREATE INDEX parent_idx ON edges (parent);
CREATE INDEX child_idx ON edges (child);

How could I solve this problem, please? Thanks in advance!




Aucun commentaire:

Enregistrer un commentaire