【发布时间】:2021-04-12 10:51:28
【问题描述】:
我需要从表nodes 中选择两个唯一的随机id 并将其插入edges 表的parent 列中。
但问题是它们有时会重复,并且需要它们始终不同,请问我该如何避免这种情况?
代码:
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");
});
表格代码:
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);
提前致谢。
【问题讨论】:
-
嗯...我不是 SQL 专家,但是如果 subselect 是随机排序的,你不能只要求
LIMIT 2并一次获取两个随机行吗?
标签: javascript mysql node.js random duplicates