PostgreSQL定时删除表数据
生活随笔
收集整理的這篇文章主要介紹了
PostgreSQL定时删除表数据
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
背景
有時(shí)候我們需要定時(shí)刪除一些表數(shù)據(jù)比如一些log表,只需要存儲(chǔ)7天的數(shù)據(jù),如果用程序,比如java來處理。就需要寫一個(gè)定時(shí)器來處理,比較麻煩。比較方便簡(jiǎn)單的做法就是使用觸發(fā)器
這里我有一個(gè) log表 想定時(shí)刪除7天前的數(shù)據(jù)。
前置處理
建表
create table logistics_xml (id bigserial not nullconstraint logistics_xml_pkprimary key,company text,order_id text,xml text,ctime timestamp(0) default now() );插入數(shù)據(jù)
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());實(shí)現(xiàn)
觸發(fā)器的一些介紹 https://www.runoob.com/postgresql/postgresql-trigger.html
這里主要將函數(shù)與表logistics_xml綁定,觸發(fā)事件為 INSERT。當(dāng)然還可以修改為 其他事件
這種做法雖然可行,但是不是很建議,因?yàn)槊看尾迦攵家獔?zhí)行
delete from logistics_xml where logistics_xml.ctime < (now() - interval ‘7 day’)
嚴(yán)重影響性能,這里基于業(yè)務(wù)作取舍
這里創(chuàng)建完成后我們?cè)贉y(cè)試插入一條數(shù)據(jù)
insert into logistics_xml(company, order_id, xml, ctime) VALUES ('66', '2323', '2', now());可以看到之前插入6月1號(hào)的數(shù)據(jù)被刪除了。
參考博客
總結(jié)
以上是生活随笔為你收集整理的PostgreSQL定时删除表数据的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python OpenCV 将同心圆环填
- 下一篇: 外包网站建设需要注意什么