繁体   English   中英

为select查询的每个结果插入另一个表

[英]Insert into a different table for each result of a select query

如果我有一个设置,如:

set @idToIgnore = (select user_id from user_field_value where user_field_id = 82 and value = 'No';

然后我运行一个选择查询:

select id from users where account_id = 10 and id != @idToIgnore;

返回~15个不同的ID值。

然后我想运行一个查询,例如:

insert into user_field_value(user_id, user_field_id, value) values (**user_id**, 82, 'Yes');

其中最终插入查询中的user_id是第二个查询中的每个id。

我认为有一种简单的方法可以做到这一点,但我无法弄明白。

为什么不在一个INSERT INTO ... SELECT ...查询中执行此操作?

INSERT INTO user_field_value(user_id, user_field_id, value) 
SELECT id, 82, 'Yes' FROM users 
WHERE account_id = 10 and id != @idToIgnore;

您也可以使用子查询而不是@idToIgnore在一个查询中@idToIgnore ,但在性能方面要小心。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM