使用SELECT ... INTO使用pyodbc创建一个新的Access表

时间:2014-05-12 15:26:04

标签: sql ms-access join pyodbc

我正在尝试基于3个不同的Access表创建一个名为Component_New的新表,并使用公共字段进行连接。

我目前有以下内容:

Make_Table = """ SELECT mapunit.mukey, copmgrp.cokey, copmgrp.copmgrpkey, copm.pmkind, copm.pmorigin, component.comppct_r, component.compname, component.majcompflag, copmgrp.pmgroupname INTO Component_Table FROM (mapunit INNER JOIN component ON (mapunit.mukey = component.mukey) INNER JOIN copmgrp ON (component.cokey = copmgrp.cokey) INNER JOIN copm ON (copmgrp.copmgrpkey = copm.copmgrpkey) INNER JOIN chorizon ON (component.cokey = chorizon.cokey)) """
cursor.execute(Make_Table)
con.commit()

似乎无法找到我的错误! 提前谢谢!

为了更好地理解我的问题:我只想知道如何获取以下添加/加入信息并使用它创建表格 - > JOINing mdb tables with pyodbc

我的以下代码在Access中工作,但是我需要将它放到Python中,以便我可以遍历多个不同的县来执行相同的添加/加入:

SELECT mapunit.mukey, copmgrp.cokey, copmgrp.copmgrpkey, copm.pmkind, copm.pmorigin, component.comppct_r, component.compname, component.majcompflag, copmgrp.pmgroupname 
INTO Component_Table 
FROM (((mapunit INNER JOIN component ON mapunit.mukey = component.mukey) 
INNER JOIN copmgrp ON component.cokey = copmgrp.cokey) 
INNER JOIN copm ON copmgrp.copmgrpkey = copm.copmgrpkey) 
INNER JOIN chorizon ON component.cokey = chorizon.cokey; 

1 个答案:

答案 0 :(得分:0)

Python Make_Table字符串中的括号不在正确的位置。在您的Python脚本示例中,您(错误地)仅将括号放在ON条件

附近
SELECT 
    mapunit.mukey, copmgrp.cokey, copmgrp.copmgrpkey, copm.pmkind, copm.pmorigin, component.comppct_r, component.compname, component.majcompflag, copmgrp.pmgroupname 
INTO Component_Table 
FROM 
    (
        mapunit 
        INNER JOIN 
        component 
            ON (mapunit.mukey = component.mukey) 
        INNER JOIN 
        copmgrp 
            ON (component.cokey = copmgrp.cokey) 
        INNER JOIN 
        copm 
            ON (copmgrp.copmgrpkey = copm.copmgrpkey) 
        INNER JOIN 
        chorizon 
            ON (component.cokey = chorizon.cokey)
    )

然后在Access中使用的后续示例中,根据Access SQL的要求,您可以围绕整个INNER JOIN构造使用括号(正确)

SELECT 
    mapunit.mukey, copmgrp.cokey, copmgrp.copmgrpkey, copm.pmkind, copm.pmorigin, component.comppct_r, component.compname, component.majcompflag, copmgrp.pmgroupname 
INTO Component_Table 
FROM 
    (
        (
            (
                mapunit 
                INNER JOIN 
                component 
                    ON mapunit.mukey = component.mukey
            ) 
            INNER JOIN 
            copmgrp 
                ON component.cokey = copmgrp.cokey
        ) 
        INNER JOIN 
        copm 
            ON copmgrp.copmgrpkey = copm.copmgrpkey
    ) 
    INNER JOIN 
    chorizon 
        ON component.cokey = chorizon.cokey

您需要调整Python代码中的SQL字符串,以便括号位于正确的位置。