PostgreSQL 数据库中查找阻塞和被阻塞的进程

SELECT
	blocked_locks.pid AS blocked_pid,
	blocked_activity.usename AS blocked_user,
	blocking_locks.pid AS blocking_pid,
	blocking_activity.usename AS blocking_user,
	blocked_activity.query AS blocked_statement 
FROM
	pg_catalog.pg_locks blocked_locks
	JOIN pg_catalog.pg_stat_activity blocked_activity ON blocked_activity.pid = blocked_locks.pid
	JOIN pg_catalog.pg_locks blocking_locks ON blocking_locks.locktype = blocked_locks.locktype 
	AND blocking_locks.DATABASE IS NOT DISTINCT 
FROM
	blocked_locks.DATABASE 
	AND blocking_locks.relation IS NOT DISTINCT 
FROM
	blocked_locks.relation 
	AND blocking_locks.page IS NOT DISTINCT 
FROM
	blocked_locks.page 
	AND blocking_locks.tuple IS NOT DISTINCT 
FROM
	blocked_locks.tuple 
	AND blocking_locks.virtualxid IS NOT DISTINCT 
FROM
	blocked_locks.virtualxid 
	AND blocking_locks.transactionid IS NOT DISTINCT 
FROM
	blocked_locks.transactionid 
	AND blocking_locks.classid IS NOT DISTINCT 
FROM
	blocked_locks.classid 
	AND blocking_locks.objid IS NOT DISTINCT 
FROM
	blocked_locks.objid 
	AND blocking_locks.objsubid IS NOT DISTINCT 
FROM
	blocked_locks.objsubid 
	AND blocking_locks.pid != blocked_locks.pid
	JOIN pg_catalog.pg_stat_activity blocking_activity ON blocking_activity.pid = blocking_locks.pid 
WHERE
	blocked_locks.GRANTED; 

SQL 查询是用于在 PostgreSQL 数据库中查找阻塞和被阻塞的进程。以下是每个字段的解释:

  • blocked_pid:被阻塞的进程的 ID。
  • blocked_user:执行被阻塞进程的用户的名称。
  • blocking_pid:阻塞其他进程的进程的 ID。
  • blocking_user:执行阻塞进程的用户的名称。
  • blocked_statement:被阻塞的 SQL 查询。

这个查询通过 pg_catalog.pg_locks 和 pg_catalog.pg_stat_activity 表连接,找出阻塞和被阻塞的进程。它通过比较阻塞和被阻塞的进程的各种属性(如数据库、关系、页面、元组、虚拟 XID、事务 ID、类 ID、对象 ID 和对象子 ID)来确定哪些进程正在阻塞其他进程。

WHERE blocked_locks.GRANTED 这一条件表示只选择那些已经获得锁但仍然被阻塞的进程。

你可能感兴趣的:(java进阶学习笔记,好记性不如烂笔头,数据库,postgresql,oracle)