2016-11-08 53 views
0

我想从我的sql语句中调用Postgres中的函数。它给了我一个“列xxx未找到”的错误。我的SQL代码如下。从sql语句调用Postgres函数给出错误

SELECT r.resource_id, r.name, owner.name, r.status, 
r.cost, r.display_unit, r.next_available_date, 
geodistance(r.latitude, r.longitude, 41.824, 71.4128) as distance 
FROM resource_item as r 
INNER JOIN base_user AS owner 
ON r.resource_owner = owner.username 
WHERE distance < 100 
ORDER BY distance, r.next_avail_date, r.name; 

我得到以下错误:

ProgrammingError: column "distance" does not exist 

功能地表距离()本身已经过测试,像下面的一个单独的语句,并能正常工作。

select geodistance(38.898556, -77.037852, 38.897147, -77.043934) as distance from incident; 

我能够得到回应,如果我把地表距离()函数在WHERE子句中,但我不知道该怎么办了ORDER BY。

我被卡住了一下。我需要评估距离并能够与输入值进行比较。我怎样才能做到这一点?

回答

1

不能在同一级查询中使用标签作为WHERE子句中的列名称。

CREATE OR REPLACE FUNCTION public.one() 
RETURNS integer 
LANGUAGE sql 
AS $function$ select 1 $function$ 

postgres=# select one() as fooa from generate_series(1,3) where one < 10; 
ERROR: column "one" does not exist 
LINE 1: ...lect one() as fooa from generate_series(1,3) where one < 10; 

你必须使用子查询

postgres=# select * from (select one() as fooa from generate_series(1,3)) s where fooa < 10; 
+------+ 
| fooa | 
+------+ 
| 1 | 
| 1 | 
| 1 | 
+------+ 
(3 rows) 
+0

我很欣赏你的快速反应。这工作像一个魅力。谢谢。 –