【问题标题】:python MySQLdb query tables iterativelypython MySQLdb迭代查询表
【发布时间】:2018-12-16 02:36:22
【问题描述】:

我正在尝试使用 Python 和 MySQLdb 查询一个表与另一个表。这是我到目前为止所得到的:

db = MySQLdb.connect( host = 'localhost', user = 'user', passwd= 
'password', db = 'vacants')

cursor = db.cursor()

numrows = cursor.rowcount

query = "SELECT address, ((20903520) * acos (cos ( radians(38.67054) )* cos( 
radians( lat ) ) * cos( radians( `long` ) - radians(-90.22942) ) + sin ( 
radians(38.67054) ) * sin( radians( lat ) ))) AS distance FROM vacants HAVING 
distance < 100;"

cursor.execute(query)

我有一张桌子,cfs,还有一张,空着。我想查看 cfs 中的每一行是否有 100 英尺内的空置物业。所以对于(弧度(38.67054)和弧度(-90.22942),我需要循环遍历cfs表,以便每个cfs经纬度替换这两个数字。(这只是我们使用的测试纬度和经度)

最后,我希望(在 .csv 中)空置物业地址、与服务调用的距离以及调用类型(它们是调用服务数据库中的两个单独字段)。像这样的东西,来自上面的查询:

这是示例数据 - 调用服务坐标:

38.595767638008056,-90.2316138251402
38.57283495467307,-90.24649031378685
38.67497061776659,-90.28415976525395
38.67650431524285,-90.25623757427952
38.591971519414784,-90.27782710145746
38.61272746420862,-90.23292862245287
38.67312983860098,-90.23591869583113
38.625956494342674,-90.18853950906939
38.69044465638584,-90.24339061920696
38.67745024638241,-90.20657832034047

还有空缺:

38.67054,-90.22942
38.642956,-90.21466
38.671535,-90.27293
38.666367,-90.23749
38.65339,-90.23141
38.645996,-90.20334
38.60214,-90.224815
38.67265,-90.214134
38.665504,-90.274414
38.668354,-90.269966

【问题讨论】:

  • 空缺中是否缺少一个字段,这是否也应包含地址-“xxxx FARLAN AV”?
  • 地址应该包含什么?你指的“这个”是什么?

标签: python mysql mysql-python


【解决方案1】:

这不是最终解决方案,因为问题中没有足够的信息(地址字段?和 20903520 ?),但它可能会通过展示如何遍历两个表并从 CFS 表中替换 lat、lon 来帮助您走上正轨进入应用于空表的查询:

import mysql.connector
cnx1 = mysql.connector.connect(user='root',password='xxxx',host='127.0.0.1',database=db)
cursor1 = cnx1.cursor()
cnx2 = mysql.connector.connect(user='root',password='xxxx',host='127.0.0.1',database=db)
cursor2 = cnx2.cursor()

sql_cfs = ('select lat,lon from cfs')

cursor1.execute(sql_cfs)
for cfs in cursor1:
    [cfs_lat,cfs_lon] = cfs
    print (cfs_lat,cfs_lon)
    query = ("SELECT address, ((20903520) * " \
        "acos (cos(radians(lon)) *" \
        "cos(radians({})) * " \
        "cos(radians({})-radians(lat)) + sin(radians(lon)) * " \
        "sin( radians({})))) AS distance " \
        "FROM vacants HAVING distance < 100;".format(cfs_lat,cfs_lon,cfs_lat))

    print (query)

    cursor2.execute(query)
    for vacants in cursor2:
        print (vacants)

【讨论】:

  • 它应该是 vacants.address(vacants 是 db 的名称以及 db 中的表的名称)和 20903520 来自将 3959 乘以 5280,因此我们可以检查 100-英尺边界(不是英里)
  • vacants 表中有哪些字段(desc vacants;)?
猜你喜欢
  • 2012-12-04
  • 2016-10-11
  • 2010-12-03
  • 1970-01-01
  • 2018-01-02
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多