Postgresql慢查询查杀

-- 获取正在执行的sql进程
select 
	c.relname 对象名称,
	l.locktype 可锁对象的类型,
	l.pid 进程id,
	l.mode 持有的锁模式,
	l.granted 是否已经对锁进行授权,
	l.fastpath,
	psa.datname 数据库名称,
	psa.wait_event 等待事件,
	psa.state 查询状态,
	backend_xmin 是否执事务快照,
	now( ) - query_start 持续时间,
	psa.query 执行语句
from
	pg_locks l
	inner join pg_stat_activity psa on ( psa.pid = l.pid )
	left outer join pg_class c on ( l.relation = c.oid )
where relkind ='r'
	and now( ) - query_start >= '00:01:00' --sql执行持续时间
order by
	query_start asc;
-----------------生成运行时间超过指定时长的sql进程灭杀语句-----------------
select 'select pg_terminate_backend(' || 进程id ||');' as "终止sql执行的语句" from (
	select distinct 进程id from (
		select 
			c.relname 对象名称,
			l.locktype 可锁对象的类型,
			l.pid 进程id,
			l.mode 持有的锁模式,
			l.granted 是否已经对锁进行授权,
			l.fastpath,
			psa.datname 数据库名称,
			psa.wait_event 等待事件,
			psa.state 查询状态,
			backend_xmin 是否执事务快照,
			psa.query 执行语句,
			now() - query_start 持续时间
		from
			pg_locks l
			inner join pg_stat_activity psa on ( psa.pid = l.pid )
			left outer join pg_class c on ( l.relation = c.oid )
			-- where l.relation = 'tb_base_apparatus'::regclass
		where    relkind ='r'
			order by query_start asc
	) aa where 持续时间 > '00:01:00'
) temp;

执行比如

select pg_terminate_backend(2877151);