I need to select two unique random id
from table nodes
and insert it in parent
column in edges
table. But problem is that they are sometimes duplicated and it need them to be always different, how could I avoid that, please?
the code:
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 a = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1 ) , (4) )";
connection.query(a, (err, res) => {
if(err) throw err;
console.log("1 edge inserted to previous data");
});
var b = "INSERT INTO `edges` (`parent`, `child`) VALUES ((SELECT `id` FROM `nodes` ORDER BY rand() LIMIT 1) , (4) )";
connection.query(b, (err, res) => {
if(err) throw err;
console.log("Another edge inserted to previous data");
});
code for the 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);
Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire