首页 > 解决方案 > Python:如何在 mysql 结果头中包含表前缀

问题描述

我需要在 python 中执行以下 SQL 查询。

SELECT table_a.company, table_b.company
FROM table_a
LEFT JOIN table_b ON table_a.id = table_b.id

但问题是,当我运行我的代码(尝试使用pymysql(cursor.execute)和pandas(pd.read_sql))时,他们显示

| company        | company        |
-----------------------------------
| <some company> | <some company> |

然而,我的期望是,输出应该是这样的:

| table_a.company        | table_b.company        |
---------------------------------------------------
| <some company>         | <some company>         |

(表头包含表前缀

我如何实现这一目标?

我的条件:

以下是我的代码:

  1. 熊猫
engine = sqlalchemy.create_engine(connection_string)
df = pd.read_sql(text(query), engine, chunksize=chunksize):
print(df)
  1. pymysql
engine = pymysql.connect(host=host, user=user, password=passw, port=port, db=database)
cursor = engine.cursor()
cursor.execute(query)
result = cursor.fetchmany(chunksize)
num_fields = len(cursor.description)
field_names = [i[0] for i in cursor.description]
df = pd.DataFrame(columns=field_names, data=result)
print(df)

任何帮助,将不胜感激

标签: pythonpython-3.xpandassqlalchemypymysql

解决方案


推荐阅读