左连接速度非常慢

scyqe7ek  于 2021-07-24  发布在  Java
关注(0)|答案(0)|浏览(156)

我有以下问题

WITH time_series AS (
  SELECT * 
  FROM generate_series(now() - interval '1days', now(), INTERVAL '1 hour') AS ts
), recent_instances AS (
  SELECT instance_id, 
         (CASE WHEN last_update_granted_ts IS NOT NULL THEN last_update_granted_ts ELSE created_ts END), 
         version, 
         4 status 
  FROM instance_application 
  WHERE group_id=$1 
  AND last_check_for_updates >= now() - interval '1days' 
  ORDER BY last_update_granted_ts DESC
), instance_versions AS (
  SELECT instance_id, created_ts, version, status 
  FROM instance_status_history 
  WHERE instance_id IN (SELECT instance_id 
                        FROM recent_instances) 
    AND status = 4 
  UNION 
  (SELECT * FROM recent_instances) 
  ORDER BY created_ts DESC
)
SELECT ts, 
       (CASE WHEN version IS NULL THEN '' ELSE version END), 
       sum(CASE WHEN version IS NOT null THEN 1 ELSE 0 END) total 
FROM (
  SELECT * 
  FROM time_series 
    LEFT JOIN LATERAL (
      SELECT distinct ON (instance_id) instance_Id, version, created_ts 
      FROM instance_versions 
      WHERE  created_ts <= time_series.ts 
      ORDER BY instance_Id, created_ts DESC
  ) _ ON true
) AS _
GROUP BY 1,2
ORDER BY ts DESC;

因此,instance\u versions子查询使用time\u series查询生成的每个时间戳值执行(请参阅最后一条select语句)。但由于某些原因,横向连接速度很慢,横向连接子查询返回的行数在12k-15k左右(对于时间序列查询的单个时间戳),这不是一个大数字,横向连接后返回的行数在250k-350k之间。有什么方法可以优化它吗?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题