【问题标题】:How to do arithmetic operations using parenthesis如何使用括号进行算术运算
【发布时间】:2021-05-28 14:52:05
【问题描述】:

我正在尝试计算数据库中(经度/纬度)中两点之间的最小距离。

我可以在 SQLite 中编写(示例):

SELECT POWER(latitude-40,2) + POWER(longitude-32,2) * 0.5
FROM example_table  

(0.5 是一个更好的近似值的校正因子)

当我尝试在 SQLAlchemy 中做同样的事情时:

db.query((models.example_table.latitude - 40) * (models.example_table.latitude - 40) + (models.example_table.longitude - 32) * (models.example_table.longitude - 32) * 0.5).first()

那么生成的 SQL 是错误的,因为它使用了 '||'而不是“+”:

INFO:sqlalchemy.engine.Engine:SELECT (example_table.latitude - ?) * (example_table.latitude - ?) || (example_table.longitude - ?) * (example_table.longitude - ?) * ? AS anon_1
FROM example_table
 LIMIT ? OFFSET ?
INFO:sqlalchemy.engine.Engine:[generated in 0.00078s] (43, 43, 32, 32, 0.5, 1, 0)
(-56.749055346000006,)

当然结果也是错误的。

我该如何解决这个问题?

【问题讨论】:

  • 您使用哪个数据库? latitudelongitude 列的数据类型是什么?
  • 我正在使用 SQLite。经度、纬度是 VARCHARs (Column(String, nullable=False))
  • || 是字符串连接,它源于您选择的列类型。虽然 SQLite 很乐意将它们转换为用于算术的数字,但并非所有 DBMS 都这样做。显式转换它们以获得正确的表达式。
  • 是的!就是这样! @IljaEverilä。我将它转换为这样的数字:db.query((cast(models.example_table.latitude, Numeric(10, 8)) - 43) * (cast(models.example_table.latitude, Numeric(10, 8)) - 43) + (cast(models.example_table.longitude, Numeric(10, 8)) - 32) * (cast(models.example_table.longitude, Numeric(10, 8)) - 32) * .5),它成功了。谢谢!

标签: python sql sqlalchemy


【解决方案1】:

括号似乎开箱即用。

在我的情况下,问题在于 2 个参数(经度、纬度)被建模为字符串(VARCHAR)。然后,DBMS 尝试连接字符串而不是数字。

解决方案是将列转换为这样的数字:

from sqlalchemy import cast, Numeric

db.query(
(cast(models.example_table.latitude, Numeric(10, 8)) - 43) *
(cast(models.example_table.latitude, Numeric(10, 8)) - 43) +
(cast(models.example_table.longitude, Numeric(10, 8)) - 32) *  
(cast(models.example_table.longitude, Numeric(10, 8)) - 32) * 
.5)

非常感谢 cmets 的人们。

【讨论】:

  • 也可以使用POWER函数:db.query(func.power(cast(model.example_table.latitude, Numeric(10, 8)) - 43), 2) + ...)
  • 那将是一个美丽。 SQLite 支持它,但我找不到“func.power”是 sql alchemy ORM。我得到:sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such function: power。我需要导入一些特殊的东西吗?
  • 嗯,我在第一条评论中提供的链接是 sqlite 的链接,所以这可能取决于您使用的 sqlite 版本。请改用POW
猜你喜欢
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-27
  • 1970-01-01
  • 1970-01-01
  • 2021-05-26
  • 1970-01-01
相关资源
最近更新 更多