复合SQL INSERT语句

时间:2012-01-22 22:49:40

标签: python mysql sql

如何组合以下两个语句来创建有效的SQL查询?

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

2 个答案:

答案 0 :(得分: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 :(得分:1)

您可以使用INSERT commandINSERT ... SELECT ... FROM变体:

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)