我有以下查询,我想计算最接近“store”类型的建筑物的用户:
WITH y AS (
SELECT t.userid as us, ST_Distance(t.thegeometry,b.thegeomtry) as dist
FROM track t,buildings b
WHERE b.type = 'store'
)
SELECT us
FROM y
WHERE dist = (SELECT MIN(dist) FROM y)
问题是,当我试图计算最小值时,它给出了0,这是不正确的。在我的数据中,id为112的用户与商店A之间的最小距离等于2441米。
答案 0 :(得分:2)
您的查询应该如下所示:
SELECT t.userid AS us
,ST_Distance(t.thegeometry, b.thegeomtry) AS dist
FROM track t
CROSS JOIN buildings b
WHERE b.type = 'store'
ORDER BY dist
LIMIT 1;
“找到最接近任何类型商店建筑物的用户” 无需CTE或聚合函数。
您可能知道,对于较大的表,查询非常昂贵,因为您有效地在表track
和buildings
之间形成有限的交叉连接 - 这意味着 O(N²)< /强>
我使用了显式CROSS JOIN
语法(相当于以逗号分隔的表格列表)来明确这一点。
答案 1 :(得分:1)
我假设ST_Distance是一个返回数字的函数,然后尝试使用此查询:
SELECT
t.userid AS us
,MIN (ST_Distance(t.thegeometry,b.thegeomtry)) AS dist
FROM track t, buildings b
WHERE b.type = 'store'
GROUP BY t.userid
ORDER BY 2
LIMIT 1
我希望你能提供帮助 Victor Zurita M。