两个表,"用户"和"轨道",我想为每个还没有用户的轨道创建一个用户(userid=0)。
我们没有用户所需的唯一电子邮件,因此旨在使用以下generate_series创建虚拟电子邮件:
insert into users (username, email)
select artist, (
select concat(generate_series(1, (SELECT COUNT(filename)
FROM tracks where userid = 0)),'@domain.com')
) as email
from tracks
where userid = 0
group by artist;
当然得到错误:
'ERROR: more than one row returned by a subquery used as an expression'
我可以使用两个SQL调用并让父代码(Python)执行循环,但我认为正确的方法是在SQL语句中。
那么如何使 Insert 语句在选择中"循环"呢?
预期输出:
id | username | email
-----+-----------------------------------------------------------+-----------------------
62 | Sam Jackson | 1@infiniteglitch.net
63 | (unknown person) | 2@infiniteglitch.net
64 | Howard Cocel J. | 3@infiniteglitch.net
您可以使用
row_number()
窗口函数执行此操作:
INSERT INTO users (username, email)
(SELECT artist, row_number() OVER () || '@domain.com'
FROM (SELECT artist
FROM tracks
WHERE userid = 0
GROUP BY artist) sq1
);
如果我很好地理解了您的问题,您需要以下查询。没有必要创建第二个查询,因为您在同一表(轨道)和同一用户标识 (0) 上操作。
insert into users (username, email)
select
artist,
concat(generate_series(1, COUNT(filename)),'@domain.com') as email
from tracks
where userid = 0
group by artist;