簡體   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