简体   繁体   中英

MySQL UPDATE Table WHERE the number of rows greater than n

In a MySQL-Table I try to update it as follows:

UPDATE MyTable SET active=2 WHERE ((active=1) AND (If the number of rows > 20 then active=2) );

I mean, the WHERE-Condition should be (active=1) and the second condition the number of rows in table should be limited to 20. Below is my approach. 方法。 Maybe it helps to understand what I'm trying to say or do:

UPDATE MyTable SET active=2 WHERE ( (active=1) AND
((SELECT id, @rownum:=@rownum + 1 as Row_Number from MyTable) JOIN (SELECT @rownum := 0) r)
, Row_Number>20)

In order to understand it better, I try to write the SQL-Statement like a code-snippet as follows:

if(Row_Number<20) {
// It's not interesting.
}else {
    for(var i=20; i<NumberOfRecords; i++) {
        active=2;
    }

}

Any idea how can I write a correct MySQL-Statement in order to accomplish my intend. Thanks in advance.

I think this is what you are after:

UPDATE MyTable
SET active=2
WHERE active=1
  AND (SELECT COUNT(*) FROM (SELECT * FROM MyTable WHERE active=2) as tbl) >20

Explanation:

This query will update active = 2 for those records which satisfy the following conditions:

  1. active=1

  2. There more 20 records in table with active=2

Result:

SQL Fiddle without updation (there are no 20 records with acive=2)

SQL Fiddle with updation (there are 20 records with acive=2)

Something like this should work:

UPDATE MyTable
SET active = 2
WHERE active = 1
AND (SELECT COUNT(*) FROM (SELECT * FROM MyTable) a) > 20

In MySQL, you have to create a subquery to circumvent the "You can't specify MyTable for update in FROM clause" error you would get otherwise. See this post for more information.

See this fiddle .

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