4

In MySQL, is it possible to update the selected records on the same query?

For eg., If the query

 SELECT * 
   FROM `table`
  WHERE field = "value"
  LIMIT 0,2

Return two rows, then on the same query, i need to increment the table's count field by 1. Is it possible?

4
  • can you be a bit more precise ? Commented Jul 26, 2012 at 10:05
  • @krammer I need to update the selected rows count by 1(to get the number of times it is displayed) after selecting the data. So i think it will better to write both the query as one Commented Jul 26, 2012 at 10:11
  • Why don't you write two seperate queries? The one you are asking for is not supported in single query Commented Jul 26, 2012 at 10:18
  • @Udhay: I don't think MySQL has anything similar to PostgreSQL's UPDATE ... RETURNING. You will have to write two queries. Commented Jul 26, 2012 at 10:19

2 Answers 2

5

Yes its possible you can write as UPDATE query as:

UPDATE my_table
SET count = count + 1
WHERE field = "value"
LIMIT 2;

or for LIMIT with offset try:

UPDATE my_table a
       INNER JOIN (SELECT id FROM my_table WHERE field = "value" LIMIT 0, 2) b
             ON a.id = b.id
SET count = count + 1;
Sign up to request clarification or add additional context in comments.

Comments

0

It's not possible. The verb SELECT only retrieves data (without modifying it); and the verb UPDATE only modifies data (without retrieving it). There is no MySQL verb that will perform both actions. You will have to use two separate statements.

However, those two statements can be encapsulated within a transaction (if supported by your storage engine) to ensure that they are conducted atomically and/or could be invoked from within a stored procedure to simplify the command that must be issued by your client. Combining the two one would have:

DELIMITER ;;

CREATE PROCEDURE select_and_update(value TEXT)
BEGIN
  START TRANSACTION;
    SELECT * FROM `table` WHERE field = value LIMIT 0,2;
    UPDATE `table` SET count = count + 1 WHERE ...;
  COMMIT;
END;;

DELIMITER ;

Then your client need merely do:

CALL select_and_update('value');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.