How can I write an UPDATE query for this SELECT query?
I have a query from my previous question (link) abou开发者_开发问答t a complex select, and my question is, how can I write an update query for result of this query, to change fet_id to some new value.
Note that this query will select rows from a queue until rcpts_count reaches 1000, (for traffic controlling). more information about this query is, in this question
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 )
If you're trying to update all the records within the set, you could write a query like this:
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;
However, depending on your activity, this isn't a safe approach, as the records returned from the query could change between the two requests.
I would recommend one of the following approaches:
- Handle the updates on the application side
- Create a temporary table with the result of the query, and update the table with a join to the temporary table
- Assuming 'fet_id' is a key unique to this batch, run the update statement first, then do a simple select based on fet_id.
I see that you are asking for MySql. This is an MsSql solution, but I think the syntax is really close (but not 100% sure of that). This sample is simplified so it can apply to any Stack user. Hopefully, you can translate to your specific dataset.
-- 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
Best of luck.
精彩评论