2012-01-22 95 views
1

如何將以下兩條語句組合起來以創建有效的SQL查詢?複合SQL INSERT語句

provider = os.path.basename(file) 

cursor.execute("""INSERT into main_app_financialstatements 
        (statement_id, provider_id***, url, date) 
        VALUES (%s, %s***, %s, %s)""", 
        (statement_id, provider***, url, date)) 

provider_id = SELECT id FROM main_app_provider WHERE provider=provider 

換句話說,我的供應商,我需要從另一個表provider_id以將其插入到main_app_financialstatements

回答

1
cursor.execute("""INSERT into main_app_financialstatements 
    (statement_id, provider_id, url, date) 
VALUES (%s, (SELECT id FROM main_app_provider WHERE provider=%s), %s, %s)""", 
    (statement_id, provider, url, date)) 
1

您可以使用INSERT ... SELECT ... FROM變體INSERT command的:

provider = os.path.basename(file) 

sql = """ 
    INSERT INTO main_app_financialstatements 
     (statement_id, provider_id, url, date) 
    SELECT %s, id, %s, %s 
    FROM main_app_provider 
    WHERE provider = %s 
    """ 
args = (statement_id, url, date, provider) 
cursor.execute(sql, args)