SQL查询半径基于链接模型的纬度和经度

时间:2017-09-24 01:52:26

标签: python sql django postgresql

我在执行一个查询时遇到问题,因为我无法将两个模型正确链接在一起。

ModelA包含与Location(latitude, longitude)表的OneToOne关系。 Postgres数据库。

查询失败:

                (
                  SELECT * FROM "myapp_location" 
                  WHERE id=location_id
                ) as location,

它给我的信息是:subquery must return only one column

以下是查询:

'''
            SELECT * FROM 
          (
                SELECT id, location_id,
                (
                  SELECT * FROM "myapp_location" 
                  WHERE id=location_id
                ) as location,
                (
                  3956 * 2 *
                  ASIN(
                    SQRT(
                      POWER(
                        SIN(({latitude}- location.latitude) *  pi()/180 / 2), 2) +
                        COS({latitude} * pi() / 180) *
                        COS(location.latitude * pi() / 180) *
                        POWER(SIN(({longitude} - location.longitude) * pi() / 180 / 2), 2)
                    )
                  )
                )
                AS distance 
                FROM {model} 
                ORDER BY distance
              ) items WHERE distance <= {miles} '''.format(latitude=latitude, longitude=longitude, miles=miles,
                                                           model=model)

有没有人有任何好的建议?非常感激。

1 个答案:

答案 0 :(得分:1)

子查询只能返回一个选定的值列

你的这个子查询无论如何都没有目的

           SELECT id, location_id,
            (
              SELECT * FROM "myapp_location" 
              WHERE id=location_id
            ) as location,

将以下内容转换为加入

像下面这样的东西可能是要走的路

SELECT *,
   ( 3956 * 2 * ASIN( SQRT( POWER( SIN(({latitude}- location.latitude) * 
pi()/180 / 2), 2) + COS({latitude} * pi() / 180) * COS(location.latitude * 
pi() / 180) * POWER(SIN(({longitude} - location.longitude) * pi() / 180 / 
2), 2) ) ) ) AS distance
FROM {model}
JOIN myapp_location ON myapp_location.id = location_id
WHERE distance <= {miles}
ORDER BY distance