【问题标题】:Postgresql update each row with a random valuePostgresql 用随机值更新每一行
【发布时间】:2016-04-06 22:08:01
【问题描述】:

这与其他问题类似,但在逐个数据库的实施中似乎有所不同。我正在使用 postgres,而 NEWID 之类的东西似乎不存在。

这就是我想要的工作:

update foo set bar = (select floor(random() * 10) + 1);

我理解为什么它没有,但我似乎无法找到适用于 Postgres 的合适解决方案。我希望 bar 的值是 1 到 10 之间的随机数,该随机数与 per 行不同。

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    我认为 Postgres 可能会优化子查询。这不行吗?

    update foo
       set bar = floor(random() * 9 + 1);  -- from 1 to 10, inclusive
    

    【讨论】:

    • 我的想法是创建一个随机函数并使用它。 CREATE OR REPLACE FUNCTION random_between(low INT ,high INT) RETURNS INT AS$$ BEGIN RETURN floor(random()* (high-low + 1) + low); END; $$ language 'plpgsql' STRICT; 然后使用函数update foo set bar = random_between(1,10)
    • @Doogle:+1 不需要这样做
    【解决方案2】:
    update foo set bar = floor(random() * 10) + 1;
    

    【讨论】:

    • 这对匿名我的帐户表的电子邮件非常有帮助:UPDATE accounts SET email = (select 'anonymized-' || (select floor(random() * 1000000) + 1 where accounts.id = accounts.id) || '@localhost')
    • 已更新。 “其中accounts.id = accounts.id”不需要。直接调用函数即可。没有“选择”。
    猜你喜欢
    • 1970-01-01
    • 2016-10-24
    • 2018-03-12
    • 1970-01-01
    • 2018-03-04
    • 1970-01-01
    • 2011-04-28
    • 2015-06-27
    相关资源
    最近更新 更多