0

我有两张桌子,stuffnonsense

create table stuff(
    id serial primary key,
    details varchar,
    data varchar,
    more varchar
);
create table nonsense (
    id serial primary key,
    data varchar,
    more varchar
);

insert into stuff(details) values
    ('one'),('two'),('three'),('four'),('five'),('six');
insert into nonsense(data,more) values
    ('apple','accordion'),('banana','banjo'),('cherry','cor anglais');

http://sqlfiddle.com/#!17/313fb/1

我想将随机值从 复制nonsensestuff。我可以使用上一个问题的答案对单个值执行此操作:SQL Server Copy Random data from a table to another

update stuff
set data=(select data from nonsense where stuff.id=stuff.id
    order by random() limit 1);

但是,我想从同一行复制多个值(dataand more),当然,子查询不会让我这样做。

我是 Microsoft SQL,我可以使用以下内容:

update stuff
set data=sq.town,more=sq.state
from stuff s outer apply
    (select top 1 * from nonsense where s.id=s.id order by newid()) sq

我读过 PostGresql 使用类似的东西,LEFT JOIN LATERAL而不是OUTER APPPLY,但简单地替换对我不起作用。

如何使用另一个表的随机行中的多个值进行更新?

4

1 回答 1

4

从 Postgres 9.5 开始,您可以从子查询中分配多个列:

update stuff
set (data, more) = (
  select data, more
  from nonsense
  where stuff.id=stuff.id
  order by random()
  limit 1
);
于 2017-07-30T01:37:33.627 回答