我在查询中遇到问题,其中一个 CTE 未返回任何行。但这很难被注意到,并且调试了很长时间。
是否可以在不注释掉主查询的情况下在 Postgres 中输出所有 CTE?
create or replace function generate_grid(
poly geometry, step double precision)
returns setof geometry as
$$ */
with
initial as (select st_xmin(poly) x0, st_ymin(poly) y0),
...(another 3 CTE skipped here)...
grid as (select point from points where st_intersects(point, poly)),
centroid as (select st_centroid(poly) point from grid where (select count(*)=0 from grid))
select * from grid
union all
select * from centroid;
$$ language sql;
在示例中,CTE centroid
被增量添加到之前运行良好的函数中。如果 grid
为空,它应该返回行。错误(我已修复)是它没有,因为它是从空的 CTE 网格
中选择的。现在,当我描述问题时,它失败的原因很明显,但是当您编写和调试时,可能会发生各种各样的事情,例如混合几何 SRID、错误 SRID 等。
最佳答案
EXPLAIN ANALYZE 看起来单独报告 CTE。
当我运行它时(Postgresql 9.4)它单独显示 CTE,并且在结果部分它确实显示从“CTE Scan on x”返回的实际行数是 0。
explain analyze
with x as (select 1 where false),
y as (select 2 where true)
select * from x, y;
返回:
Nested Loop (cost=0.02..0.07 rows=1 width=8) (actual time=0.002..0.002 rows=0 loops=1)
Output: x."?column?", y."?column?"
CTE x
-> Result (cost=0.00..0.01 rows=1 width=0) (actual time=0.000..0.000 rows=0 loops=1)
Output: 1
One-Time Filter: false
CTE y
-> Result (cost=0.00..0.01 rows=1 width=0) (never executed)
Output: 2
-> CTE Scan on x (cost=0.00..0.02 rows=1 width=4) (actual time=0.002..0.002 rows=0 loops=1)
Output: x."?column?"
-> CTE Scan on y (cost=0.00..0.02 rows=1 width=4) (never executed)
Output: y."?column?"
Planning time: 0.034 ms
Execution time: 0.018 ms
我不知道解释总是会像这样显示数据,我怀疑这取决于 Postgresql 决定如何优化查询,但这应该是一个很好的起点。
在 http://www.postgresql.org/docs/current/static/sql-explain.html 解释文档
关于sql - 如何在 PostgreSQL 中调试公用表表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36648776/