我对PostgreSQL有点新手,但我对MySQL有一些经验。
Postgres正在向我显示错误 - COLUMN不存在,但这是由AS创建的“虚拟列”。
代码,在MySQL中运行良好:
SELECT place.*, 3956 * 2 * ASIN(SQRT( POWER(SIN((place.lattitude - $1) * pi() / 180 / 2), 2) + COS($2 * pi() / 180) * COS(place.lattitude * pi() / 180) *POWER(SIN(($3 - place.longitude) * pi() / 180 / 2), 2) )) AS "distance" FROM place WHERE place.longitude BETWEEN $4 AND $5 AND place.lattitude BETWEEN $6 AND $7 HAVING "distance" < $8 ORDER BY "distance" LIMIT 10
但Postgres显示列“距离”不存在。
我该如何重写它? (请写完整的SQL查询,而不是“如何”)
$ number 是可变的(针对SQL注入)
由于
答案 0 :(得分:1)
使用子查询:
SELECT p.*
FROM (SELECT place.*, 3956 * 2 * ASIN(SQRT( POWER(SIN((place.lattitude - $1) * pi() / 180 / 2), 2) + COS($2 * pi() / 180) * COS(place.lattitude * pi() / 180) *POWER(SIN(($3 - place.longitude) * pi() / 180 / 2), 2) )) AS "distance"
FROM place
WHERE place.longitude BETWEEN $4 AND $5 AND
place.lattitude BETWEEN $6 AND $7
) p
WHERE "distance" < $8
ORDER BY "distance"
LIMIT 10;
您不希望在MySQL中使用子查询,因为它实现了中间结果。其他数据库在优化查询方面更加智能,并且不一定实现子查询。