【问题标题】:how to use one query output into other query in python?如何将一个查询输出用于python中的另一个查询?
【发布时间】:2020-07-14 13:18:39
【问题描述】:

我正在尝试将一个查询输出用于另一个。但没有得到正确的结果。你能帮我怎么做吗?

例子:

query1 = "select distinct lower(tablename) as tablename from medaff.imedical_metadata where object_type = 'View'"

上述查询的输出是:

tablename
vw_mdcl_insght
vw_fbms_interactions

我想在其他查询中使用上述输出。像这样-

query2 = "select * from medaff.imedical_business_metadata where objectname in ('vw_mdcl_insght', 'vw_fbms_interactions')"

这部分在python中怎么做?

我正在使用下面的代码来运行查询:

conn = redshift_conn()

with conn.cursor() as cur:
      query1 = "select distinct lower(tablename) as tablename from medaff.imedical_metadata where object_type = 'View'"
      cur.execute(sql_query)
      result = cur.fetchall()
      print(result)
      conn.commit()

      query2 = "select * from medaff.imedical_business_metadata where objectname in ('vw_mdcl_insght', 'vw_fbms_interactions')"
      cur.execute(sql_query)
      result = cur.fetchall()
      print(result)
      conn.commit()

【问题讨论】:

    标签: python sql python-3.x amazon-redshift


    【解决方案1】:

    我认为您可以使用in 查询:

    select ibm.*
    from medaff.imedical_business_metadata ibm
    where ibm.objectname in (select lower(im.tablename) as tablename
                             from medaff.imedical_metadata im
                             where im.object_type = 'View'
                            );
    

    最好让数据库来做。

    【讨论】:

    • 关系“ibm”不存在
    • @Shivam 。 . .嗯? ibm 是在from 子句中明确定义的表别名。
    【解决方案2】:

    我使用了以下代码:

    query = "select distinct lower(tablename) from medaff.imedical_metadata where object_type = 'View'"
    cur.execute(query)
    res = cur.fetchall()
    print(res)
    res = tuple([item[0] for item in res])
    res = str(res)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-18
      • 1970-01-01
      • 2022-11-19
      • 1970-01-01
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多