【问题标题】:Update randomly selected row in SQLite更新 SQLite 中随机选择的行
【发布时间】:2009-06-18 05:58:15
【问题描述】:

我有一个表格,里面有一个特定的值 - 默认情况下它设置为 -1,但我想将它更改为 0 随机行。

这个操作的正确查询是什么?

这是我尝试过的:

UPDATE statuses SET status = 0
WHERE word_id = (
      SELECT word_id FROM statuses WHERE status = -1 ORDER BY RANDOM() LIMIT 1
)

【问题讨论】:

  • mail-archive.com/sqlite-users@sqlite.org/msg14657.html> 有帮助吗?
  • 我不确定,“ORDER BY RANDOM()”有什么问题?
  • @Ilya 取决于您要排序的行数(排序成本很高)以及此查询的运行频率。您的问题的措辞表明您的查询确实存在问题。
  • 你尝试的时候发生了什么?有问题吗?错误?

标签: sql sqlite


【解决方案1】:

嗯,我刚刚制作了一个示例表,您的查询似乎可以正常工作:

sqlite> create table statuses (word_id, status default -1);
sqlite> insert into statuses (word_id) values (1);
sqlite> insert into statuses (word_id) values (2);
sqlite> insert into statuses (word_id) values (3);
sqlite> insert into statuses (word_id) values (4);
sqlite> insert into statuses (word_id) values (5);
sqlite> select * from statuses;
1|-1
2|-1
3|-1
4|-1
5|-1
sqlite> UPDATE statuses SET status = 0
   ...> WHERE word_id = (
   ...>       SELECT word_id FROM statuses WHERE status = -1 ORDER BY RANDOM() LIMIT 1
   ...> );
sqlite> select * from statuses;
1|-1
2|-1
3|0
4|-1
5|-1

因此,换句话说,您的查询是正确的 - 您的错误可能在代码的其他地方。

【讨论】:

    猜你喜欢
    • 2011-05-06
    • 2012-08-29
    • 2023-04-03
    • 2013-07-19
    • 1970-01-01
    • 1970-01-01
    • 2010-12-05
    • 2019-03-17
    • 2012-06-20
    相关资源
    最近更新 更多