[英]How can I write an UPDATE query for this SELECT query?
我上一個問題( 鏈接 )有一個關於復雜選擇的查詢,我的問題是,如何為該查詢的結果編寫一個更新查詢,以將fet_id更改為一些新值。
請注意,此查詢將從隊列中選擇行,直到rcpts_count達到1000(用於流量控制)。 關於這個查詢的更多信息是在這個問題上
SELECT NULL AS msg_id, NULL AS total, NULL AS found
FROM dual
WHERE (
@total :=0
OR
@found :=0
)
UNION
SELECT msg_id, @total AS total, @found :=1 AS found
FROM messages_queue
WHERE (
@total := @total + rcpts_count
)
AND @total <1000
UNION
SELECT msg_id, rcpts_count AS total, 0 AS found
FROM messages_queue
WHERE IF( @found =0, @found :=1, 0 )
我看到您正在請求MySql。 這是一個MsSql解決方案,但我認為語法確實很接近(但並非100%肯定)。 此示例已簡化,因此可以應用於任何Stack用戶。 希望您可以轉換為特定的數據集。
-- sample table
create table x
(col1 int identity(1, 1)
,col2 varchar(50))
-- sample data
insert into x (col2) values
(null)
,(null)
,(null)
,(null)
,(null)
-- update from select
update x
set x.col2 = 'even'
from x as [t2]
where
col1 = t2.col1
and t2.col1 % 2 = 0
-- show results
select * from x
-- clean up
drop table x
祝你好運。
如果您嘗試更新集合中的所有記錄,則可以編寫如下查詢:
UPDATE message_queue mq
INNER JOIN (
SELECT NULL AS msg_id, NULL AS total, NULL AS found
FROM dual
WHERE (
@total :=0
OR
@found :=0
)
UNION
SELECT msg_id, @total AS total, @found :=1 AS found
FROM messages_queue
WHERE (
@total := @total + rcpts_count
)
AND @total <1000
UNION
SELECT msg_id, rcpts_count AS total, 0 AS found
FROM messages_queue
WHERE IF( @found =0, @found :=1, 0 )
) msgs ON msgs.msg_id = mq.msg_id
SET mq.fet_id = 12345;
但是,根據您的活動,這不是一種安全的方法,因為從查詢返回的記錄可能會在兩個請求之間發生變化。
我建議使用以下方法之一:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.