PostgreSQL定时删除表数据
生活随笔
收集整理的這篇文章主要介紹了
PostgreSQL定时删除表数据
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
背景
有時候我們需要定時刪除一些表數據比如一些log表,只需要存儲7天的數據,如果用程序,比如java來處理。就需要寫一個定時器來處理,比較麻煩。比較方便簡單的做法就是使用觸發器
這里我有一個 log表 想定時刪除7天前的數據。
前置處理
建表
create table logistics_xml (id bigserial not nullconstraint logistics_xml_pkprimary key,company text,order_id text,xml text,ctime timestamp(0) default now() );插入數據
insert into logistics_xml(id, company, order_id, xml, ctime) VALUES (1, '232', '2323', '2424', now()); insert into logistics_xml(company, order_id, xml, ctime) VALUES ('232', '2323', '2', '2021-06-01 03:05:53'); insert into logistics_xml(company, order_id, xml, ctime) VALUES ('66', '2323', '2', now());實現
觸發器的一些介紹 https://www.runoob.com/postgresql/postgresql-trigger.html
這里主要將函數與表logistics_xml綁定,觸發事件為 INSERT。當然還可以修改為 其他事件
這種做法雖然可行,但是不是很建議,因為每次插入都要執行
delete from logistics_xml where logistics_xml.ctime < (now() - interval ‘7 day’)
嚴重影響性能,這里基于業務作取舍
這里創建完成后我們再測試插入一條數據
insert into logistics_xml(company, order_id, xml, ctime) VALUES ('66', '2323', '2', now());可以看到之前插入6月1號的數據被刪除了。
參考博客
總結
以上是生活随笔為你收集整理的PostgreSQL定时删除表数据的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python OpenCV 将同心圆环填
- 下一篇: 第17章 其他数据库日志【4.日志与备份