首页 > 解决方案 > 在 Python 中传递 MySQL CREATE TABLE SELECT 查询会引发语法错误

问题描述

我正在尝试在 Python 的循环中将查询传递给 sql:

for i in superstar.iloc[:, 0]:

    cursor = conn.cursor()

    loop_cmd = f"""
    DROP TABLE IF EXISTS superstar_fwdPlusbwd_{i}; \
    CREATE TABLE superstar_fwdPlusbwd_{i} \
    SELECT a.*, b.CitingPatPublNr as fwd_CitingPatPublNr, c.CitedPatPublNr as bwd_CitedPatPublNr \
    from orbisFirm_focals_basic_feed a \
    left join patents.Patents_ForwardCitations b on a.focal_PatPublNr = b.PatPublNr \
    left join patents.Patents_BackwardCitations c on a.focal_PatPublNr = c.PatPublNr \
    where focal_PatPublNr = "{i}"
    ;
     """
    
    cursor.execute(loop_cmd)

但这会引发语法错误:

ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CREATE TABLE `superstar_fwdPlusbwd_AU2002310193B2`     SELECT a.*, b.CitingPatPu' at line 1")

这似乎是 MySql 中的语法错误,但此查询在 MySQL Workbench 中有效。请帮忙,谢谢!

标签: pythonmysqlselectcreate-table

解决方案


您还没有传递 Mysql 表中列的参数。您应该使用正确的语法来创建表指定列名、类型等


推荐阅读