You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Python执行SQL查询后按关联表拆分得到独立数组格式结果

解决方案

你无需修改现有SQL语句,只需对返回的扁平化查询结果做一次字段分组处理即可,具体实现代码如下:

import datetime

def split_result_by_table(flat_row):
    # 初始化按表拆分的结果结构
    res = {
        "LocationModel": {},
        "LocationType": {},
        "Parent": {}
    }
    for key, val in flat_row.items():
        # 处理datetime类型转字符串,和你预期的输出格式对齐
        if isinstance(val, datetime.datetime):
            val = val.strftime("%Y-%m-%d %H:%M:%S")
        # 按字段名前缀判断所属表
        if key.startswith("LocationType."):
            _, field = key.split(".", 1)
            res["LocationType"][field] = val
        elif key.startswith("Parent."):
            _, field = key.split(".", 1)
            res["Parent"][field] = val
        else:
            # 无关联表前缀的字段统一归属主表LocationModel
            res["LocationModel"][key] = val
    return res

# 调用示例
# 假设你执行SQL后拿到的原始结果是raw_result
raw_result = [{'id': 54522, 'location_type_id': 5, 'parent_id': 7544, 'name': 'Koln - Zollstock', 'name_deu': 'Köln - Zollstock', 'lat': '50.905591', 'lng': '6.95257', 'is_active': 1, 'is_use_for_avg': 0, 'created': datetime.datetime(2018, 9, 18, 9, 54, 21), 'modified': datetime.datetime(2018, 9, 18, 9, 54, 21), 'LocationType.id': 5, 'LocationType.name': 'Municipality', 'LocationType.is_active': 1, 'priority': 5, 'LocationType.is_use_for_avg': 0, 'LocationType.created': datetime.datetime(2014, 2, 10, 23, 22, 27), 'LocationType.modified': datetime.datetime(2014, 2, 10, 23, 22, 27), 'Parent.id': 7544, 'Parent.location_type_id': 4, 'Parent.parent_id': 297, 'Parent.name': 'Koln', 'Parent.name_deu': 'Köln', 'Parent.lat': '52.5200', 'Parent.lng': '13.4050', 'Parent.is_active': 1, 'Parent.is_use_for_avg': 0, 'Parent.created': datetime.datetime(2018, 9, 18, 8, 17, 15), 'Parent.modified': datetime.datetime(2018, 9, 18, 8, 17, 15)}]
formatted_result = [split_result_by_table(row) for row in raw_result]

补充说明

你当前返回结果中的priority字段属于LocationType但没有带表名前缀,会被默认归类到LocationModel中,可通过两种方式修正:

  1. 修改SQL语句,给该字段加别名:LocationType.priority AS "LocationType.priority"
  2. 直接在上述分组逻辑中新增判断:如果key == "priority",就归属到res["LocationType"][key] = val

如果后续你使用SQLAlchemy等ORM框架操作数据库,可以直接配置表关联关系,查询时会自动返回分层结构的对象,无需手动做字段拆分。

内容的提问来源于stack exchange,提问作者Parth Shah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 23:42:03