在添加这两行或其中任何一行后,查询超时
AND final IS NOT NULL
ORDER BY tmodified ASC
查询持续运行超过10分钟......并且超时。
如果我删除上面两行,它会在1毫秒内返回结果,这可以正常工作。
任何想法如何使以上两行使用以下查询?
表table_h有3600万条记录,在此表中
column final is numeric(10,5)
column tmodified is bigint, Timestamp
我正在使用Postgres 9.4
这是完整的查询。
SELECT DISTINCT t.cid, h.a, am.b, u2.c, u.d, h.e, ie.f, im.g FROM table_am as am
INNER JOIN table_t as t on (t.id = am.id AND t.type = am.type)
INNER JOIN table_h AS h on h.iid = t.id
INNER JOIN table_u AS u ON u.id = h.uid
INNER JOIN table_u AS u2 ON u2.id = h.lu
INNER JOIN table_im AS im ON im.asid = am.sid
INNER JOIN table_ie AS ie ON ie.uid = u.uid
INNER JOIN table_g AS g ON g.id = h.oldid
WHERE h.final >= 0
AND h.final IS NOT NULL
AND h.tmodified >= 1499903419
AND ie.p = im.p
AND h.sr IN ('x', 'y', 'z')
AND h.id = (SELECT id FROM table_h WHERE oldid = h.oldid AND final >= 0
AND final IS NOT NULL -- Issue is here and
ORDER BY tmodified ASC -- Issue is here
LIMIT 1)
AND h.id NOT IN (SELECT id FROM table_m WHERE tmodified > 1499903419)
答案 0 :(得分:1)
尝试使用连接替换相关的子查询,如下所示:
SELECT ...
FROM table_am as am
...
INNER JOIN table_g AS g ON g.id = h.oldid
INNER JOIN
(
SELECT id, oldid, MIN(tmodified) AS min_mod
FROM table_h
WHERE final >= 0 AND final IS NOT NULL
GROUP BY id, oldid
) t
ON h.id = t.id AND
h.oldid = t.oldid AND
h.tmodified = t.min_mo
请注意,我们也可以使用行号或其他分析函数表达这一点,但希望这为您提供了一个开始的地方。
答案 1 :(得分:1)
好吧,我可以解决你的一半问题。条件:
AND h.final IS NOT NULL
不需要。条件:
h.final >= 0
已考虑到这一点。
如果剩余查询返回的速度很快,则使用子查询或cte,然后按:
排序with cte as (
select . . ., t.modified
)
select cte.*
from cte
order by modified;
答案 2 :(得分:0)
吸尘所有涉及表将解决问题。
VACUUM ANALYZE table_am;
VACUUM ANALYZE table_t;
VACUUM ANALYZE table_h;
VACUUM ANALYZE table_u;
VACUUM ANALYZE table_im;
VACUUM ANALYZE table_ie;
VACUUM ANALYZE table_g;
VACUUM ANALYZE table_m;
参考:https://www.postgresql.org/docs/9.4/static/sql-vacuum.html