简体   繁体   中英

MySQL select and update multiple rows from same table

Generally I want to select rows from orders table in my database, that were created after some date, and then update office_id field for all of selected rows to the specific value 12 . My MySQL version is 5.5.43. At firs I was trying to put it in one SQL statement like so:

UPDATE `order`
SET office_id = 12
WHERE id IN (  
  SELECT id
  FROM  `order` 
  WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' ) 
);

And I was getting error: #1093 - You can't specify target table 'order' for update in FROM clause .

Next I tried to do this with SELECT .. FOR UPDATE statment like so:

START TRANSACTION;

SELECT id
FROM  `order` 
WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' ) 
FOR UPDATE;

UPDATE `order`
SET office_id = 12
WHERE id IN ( id );

COMMIT;

Which worked, but if SELECT .. FOR UPDATE statement returns no rows, then office_id = 12 would be applied to all rows in orders table, which I defenetely don't want.

I'm looking for help in modification 1st or 2nd solution for propper working.

It's much simpler than you're making it. You can apply a WHERE clause directly to an UPDATE statement.

UPDATE `order`
    SET office_id = 12
    WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' );

If id can be duplicated in order , then you can express the query using a join :

UPDATE `order` o JOIN
       (SELECT distinct o.id
        FROM  `order` o
        WHERE created_at >= DATE_FORMAT( '2014-07-02 00:00:00', '%Y.%m.%d 00:00:00' 
       ) oo
       ON o.id = oo.id
    SET o.office_id = 12;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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