简体   繁体   中英

Update Table Column in Multiple Rows based on a Selection in SQL

I have selected a group of rows using Select statement in SQL , and I'm trying to figure out how to update a column in this table to a value based on said selection .

The Selection:

SELECT user.userID FROM user WHERE user.status = '1' or user.status = '2' LIMIT 1000 OFFSET 50;

The Update:

UPDATE user SET user.status = '3';

The end result I am looking for is the status column of all the selected users be updated to '3'. I want to be able to do this in one SQL query and not have to loop or anything.

Thanks for any insight!

UPDATE:

Sorry! I forgot to add the offset . I want to select the rows after the first 50 returned rows. So I want all the rows after the first 50 that match the criteria, to have the status column changed to 3.

OLD

UPDATE user SET user.status = '3' WHERE user.status = '1' or user.status = '2';

Please try this query...

NEW

After Edit Question (As per offset)

try this below query for your offset.

UPDATE user SET user.status = '3' where  user.userID NOT IN(Select
userid from 
(SELECT userID as userid FROM user WHERE status = '1' or status = '2' LIMIT 50) 
as temptbl);
UPDATE user SET user.status = '3' where user.status in ('1', '2');

更新:

UPDATE user SET user.status = '3' where user.userID in (SELECT user.userID FROM user WHERE user.status = '1' or user.status = '2' LIMIT 1000 OFFSET 50);

请尝试这个

UPDATE user SET user.status = '3' WHERE user.status IN ( '1' , '2' )

new:

Use two subselects (Thanks to Yograj Sudewad for poiting me to my mistake)

UPDATE user 
SET user.status = '3'
WHERE user.userID IN (
    SELECT userId 
    FROM (
        SELECT user.userID 
        FROM user 
        WHERE user.status = '1' or user.status = '2' 
        LIMIT 1000 OFFSET 50
    ) AS tableWithNoName
)

old:

You could just use the WHERE part from your SELECT in your UPDATE as well. Like so

UPDATE user 
SET user.status = '3'
WHERE user.status = '1' 
    OR user.status = '2';

But if you want the UPDATE from the uid list, then:

<?php
// The uid list from the select may be 
$uid_list = array(1,4,7,12,401);
// then you could make
$sql = "
UPDATE user 
SET user.status = '3'
WHERE user.userID IN (" . implode(',', $uid_list) , ")

";

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