mysql - Mysql如何使用count函数更新n行?
问题描述
在下表中,如果同一 orgid 的总记录超过 500,我想设置 delete = true,并且我想根据 createdate 进行设置,这样如果记录超过 500,则旧记录将被删除,并使该 orgid 的总记录为 500。
这是我的桌子
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
推荐阅读
- django - /etc/nginx/conf.d/default.conf:1 中不允许使用“http”指令
- reactjs - 使用 React 测试库按组件名称进行测试
- java - Java Socket 和 ServerSocket 通信死锁
- python - avro-python3 不提供模式演变?
- php - 我将如何解析一个存储在其中的字符串的 php 变量?
- node.js - 如何将环境变量从文件传递到节点命令
- python - 如何修复mysqlclient错误,无法下载,(wndows os)
- ios - 跟踪 iOS 应用的移动数据和 WiFi 使用情况
- aws-cloud9 - AWS-Cloud9 时间积累太快
- google-sheets - 如何使工作表过滤器仅在 G-Sheets 中显示带有多个变量的复选标记行