Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Postgresql 在Postgres中使用floor()高效地从大表中选择_Postgresql - Fatal编程技术网

Postgresql 在Postgres中使用floor()高效地从大表中选择

Postgresql 在Postgres中使用floor()高效地从大表中选择,postgresql,Postgresql,我有两个表:一个是自然数上x和y列的正方形,另一个是第一个表创建的网格上的点。模式示例: 网格表 id | x | y ------------ 123 | 1 | 1 234 | 1 | 2 345 | 2 | 1 456 | 2 | 2 然后,点表: id | x | y ---------------- 12 | 1.23 | 1.23 23 | 2.89 | 1.55 当前,使用此查询: SELECT g.* FROM grid as g, point

我有两个表:一个是自然数上x和y列的正方形,另一个是第一个表创建的网格上的点。模式示例:

网格表

id  | x | y
------------  
123 | 1 | 1  
234 | 1 | 2
345 | 2 | 1   
456 | 2 | 2
然后,
点表

id |   x  |  y  
----------------
12 | 1.23 | 1.23
23 | 2.89 | 1.55  
当前,使用此查询:

SELECT g.* FROM grid as g, points as p  
WHERE p.id=23 AND floor(p.x)=g.x AND floor(p.y)=g.y;
我得到了预期的结果,即id为
23
的点所在的网格正方形(id为
345
的网格);但是,当表
网格
有10000000行时(我目前的情况),这个查询速度非常慢,即几秒钟的时间

我已经找到了一个解决办法,但很难看:

SELECT g.* FROM grid as g, points as p  
WHERE p.id=23 AND (p.x-.5)::integer=g.x AND (p.y-.5)::integer=g.y;  

我再次得到了预期的结果,在11毫秒内,但这感觉有点不对劲。有没有更干净的方法?感谢您的帮助

您可以使用CTE,因为它只评估一次

WITH p2 AS (select floor(p.x) x, 
                   floor(p.y) y 
            from points  p 
            where p.id=23)
SELECT  g.* 
FROM grid g
INNER JOIN  p2
ON p2.x=g.x and p2.y=g.y