Mysql 如何使用计数函数更新n行?

Mysql How to update n rows using count function?

在下面的table中,如果同一个 orgid 的总记录数超过 500,我想设置 delete = true 我想根据 createdate 来做,如果记录超过 500,旧记录将被删除,并使该 orgid 的总记录为 500。

这是我的 table

Table A
+----+-------+------------------+--------+------------+
| id | orgid | transactionvalue | delete | createdate |  
+----+-------+------------------+--------+------------+
|  1 |     1 |              123 | false  | 05-16-2020 |  
|  2 |     1 |              412 | false  | 07-16-2020 |  
|  3 |     2 |              762 | false  | 07-16-2020 |  
+----+-------+------------------+--------+------------+

这是我正在尝试的查询

update A 
set 
  delete = true 
where orgid = 1 
and (select count(*) as records 
      from (select * 
            from A order by createdate
    ) as pseudotable)) >500

使用子查询并加入更新

   UPDATE tablea
            INNER JOIN
        (select orgid, count(*) cnt from tablea group by orgid
        ) b ON tablea.orgid = b.orgid 
    SET 
        delete = 'true'
    where cnt>500

您可以使用 row_number() 找到每个组织的第 500 条记录,然后使用该信息:

update tablea a join
       (select a2.org_id, a2.created_date as cutoff_created_date
        from (select a2.*,
                     row_number() over (partition by a2.org_id order by create_date desc) as seqnum
              from tablea a2
             ) a2
        where a2.seqnum = 500
       ) a2
       on a.org_id = a2.org_id and and
          a.created_date < a2.cutoff_created_date
    set delete = true;

我没有尝试所有其他答案,它们可能是正确的,但这对我有用

update A 
set `delete` = true 
where orgid = 1 AND id IN (
SELECT id FROM  A where orgid = 1
order by createdate DESC
LIMIT 500,18446744073709551615);