【问题标题】:How to avoid duplicated random id selection in MySQL?如何避免 MySQL 中重复的随机 id 选择?
【发布时间】: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


【解决方案1】:

您不想要两个连续的随机选择,因为第二个随机选择返回与第一个相同的行的可能性非零。我认为您应该一次获取两行:

INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2;

因此,您的代码将只执行一个查询,而不是两个:

var a = "INSERT INTO `edges` (`parent`, `child`) SELECT `id`, 4 FROM `nodes` ORDER BY rand() LIMIT 2";

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

当我在本地设置你的数据库并运行上面的代码时,我得到了一个成功的插入:

Database Connected!
2 edges inserted to previous data

当我在控制台中查询数据库时,我得到:

mysql> select * from edges;
+--------+-------+
| parent | child |
+--------+-------+
|      2 |     4 |
|      3 |     4 |
+--------+-------+
2 rows in set (0.00 sec)

【讨论】:

  • 感谢您的回答,但它显示此错误Subquery returns more than 1 row
  • @ismsm 上面的代码有效。您实际上是在使用我提供的查询,还是仍在使用VALUES (...) 语法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-15
  • 2023-03-23
  • 1970-01-01
  • 1970-01-01
  • 2010-12-19
  • 2018-03-26
  • 1970-01-01
相关资源
最近更新 更多