表:
工作站
用户
我的业务需求是:我想要两个新的工作站,名为"A“和"B”,用于每个仍然没有工作站的用户(在工作站表中没有条目)。
所以,这就像是每人一份。
对于我在select中找到的每个用户,我想做两个插入(对于'A‘和'B'),如
insert into workstation(name, user_id)
values('A', select id from user where id not in (select user_id from workstation));这不起作用,因为'A‘是硬编码的,而select检索多个id。即使对'A’有效,'B‘也肯定会失败。
发布于 2019-11-20 15:00:05
可以从select语句直接插入多条记录,如下所示
insert into workstation(name, user_id)
select 'A', id from user where id not in (select user_id from workstation)
union
select 'B', id from user where id not in (select user_id from workstation);若要同时将它们添加到'A'和'B'中,请同时选择“在同一语句中”,以确保将它们添加到'A'和'B'工作站中。
有关更多详细信息,您可以在postgre 文档中选中insert
发布于 2019-11-20 15:25:01
希望这对你来说更准确。
insert into workstation(name, user_id)
select 'A', id from user where (select count(*) from workstation where name = 'A' and user_id = user.id) = 0
union
select 'B', id from user where (select count(*) from workstation where name = 'B' and user_id = user.id) = 0发布于 2019-11-20 15:14:32
从id不在的用户处选择id (从工作站选择user_id )可能返回多个记录,我猜这就是它失败的地方。您是否尝试过将提取的记录限制为单个记录?语法可能不正确:
insert into workstation(name, user_id) values('A', (select id from user where id not in (select user_id from workstation) Limit 1))即使工作站表中还没有多个记录,这也只能得到一个尚未出现的记录。
https://stackoverflow.com/questions/58957193
复制相似问题