Mysql如何使用count函数更新n行?
在下表中,如果同一组织的总记录超过500条,我想将delete设置为true 我想根据createdate来做,这样如果记录超过500条,旧记录就会被删除,并使该orgid的记录总数达到500条 这是我的桌子Mysql如何使用count函数更新n行?,mysql,sql,stored-procedures,sql-update,Mysql,Sql,Stored Procedures,Sql Update,在下表中,如果同一组织的总记录超过500条,我想将delete设置为true 我想根据createdate来做,这样如果记录超过500条,旧记录就会被删除,并使该orgid的记录总数达到500条 这是我的桌子 Table A +----+-------+------------------+--------+------------+ | id | orgid | transactionvalue | delete | createdate | +----+-------+---------
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
使用子查询和联接更新
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;
您可以使用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);
我没有尝试所有其他答案,它们可能是正确的,但这对我来说是有效的
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);
您可以通过为3家公司提供样本数据来澄清和简化5家公司各保留2.您正在运行的MySQL版本是什么?@EricBrandt 8.0.17您可以通过为3家公司提供样本数据来澄清和简化5家公司各保留2.您正在运行的MySQL版本是什么?@EricBrandt 8.0.17Createdate必须在这里的某个地方提供功能?订购createdate描述?createdate必须在这里的某个地方出现?按createdate描述订购?