最近生產上的 PostgreSQL 發現有幾個進程一直長時間運行,經過 top 命令能看到不少對應 postgres 進程都跑到接近 100%,並且 TIME+ 時間很長。sql
最終找到了查看 CPU 執行時間過長是哪一個語句。我這裏當前使用的數據庫版本是PostgreSQL 9.6.6。數據庫
# ps aux | grep postgres | sort -n -r -k 3 | head -10 | awk '{print $2, $3}'
postgres=# SELECT procpid, START, now() - START AS lap, current_query FROM ( SELECT backendid, pg_stat_get_backend_pid (S.backendid) AS procpid, pg_stat_get_backend_activity_start (S.backendid) AS START,pg_stat_get_backend_activity (S.backendid) AS current_query FROM (SELECT pg_stat_get_backend_idset () AS backendid) AS S) AS S WHERE current_query <> '<IDLE>' and procpid=22687 ORDER BY lap DESC; procpid | start | lap | current_query ---------+------------------------------+-----------------+-------------------------------------------------------------------------------------------------------- 22687 | 2019-04-09 10:57:21.96082+08 | 00:36:07.920674 | EXPLAIN ANALYSE SELECT a.id, + | | | a.content, + | | | a.entity_id, + | | | a.entity_type, + | | | a.start_date, + | | | a.due_date, + | | | a.image_id, + | | | a.sg_status_list, + | | | a.project_id, + | | | a.cached_display_name, + | | | a.dependency_violation, + | | | a.sg_progress_info, + | | | a.inventory_date, + | | | a.step_id, + | | | a.time_logs_sum, + | | | a.est_in_mins, + | | | a.sg_production_bid_id, + | | | a.sg_production_bid_type, + | | | a.pinned, + | | | a.splits, + | | | a.filmstrip_image_id, + | | | c.cached_display_name AS _grp_c_cached_display_name, + | | | CASE WHEN c.id IS NULL THEN NULL ELSE 'Project' END AS _grp__project_, + | | | c.id AS _grp_c_id + | | | FROM tasks a + | | | LEFT JOIN display_name_caches b ON (b.entity_type = 'Project' AND b.entity_id = a.project_id)+ | | | LEFT JOIN projects c ON (c.id = a.project_id AND c.retirement_date IS NULL) + | | | WHERE ((a.sg_disabled = 'f' AND (a.project_id = ANY +
只須要在查詢語句中的 procpid 輸入對應查詢到的進程 id 便可,上面 SQL 語句中我查詢的進程 id 號是 22687,上面的查詢語句只是查詢其中一個進程的結果。查詢結果中幾個字段的含義以下:
procpid:進程id
start:進程開始時間
lap:通過時間
current_query:執行中的sqlide