【问题标题】:Use the output of one query to input another query python使用一个查询的输出输入另一个查询 python
【发布时间】:2015-08-05 18:54:26
【问题描述】:

以下是我的代码,

connect=Tl.connection.Connection()
a= connnect.connect('dbname', schema='schemaname')
q='''select id, id1 from table1;'''
w= Tl.datatool.todf(a(q))
id=w.id
id1=w.id1

现在对于每个 id 和 id1,我需要执行第二个查询,它应该像一个循环,应该存储在一个数据框中,

我正在寻找的查询是,

select id2 from table2 where x=id and y=id1;

我在努力,

for i in id:
    for j in id1:
        q2='''select id2 from table2 where x=%i and y=%i;''' (int(id), int(id1))
        print a(q2)

但我无法获得准确的输出。我收到以下错误,

   TypeError: 'str' object is not callable

我正在寻找的输出是,对于 id 和 id1 的所有值,我需要获取 id2 并且所有值都应该存储在数据框中。

谁能帮我做这件事?

【问题讨论】:

    标签: python mysql python-2.7


    【解决方案1】:

    您忘记使用% 运算符:

        q2='''select id2 from table2 where x=%i and y=%i;''' (int(id), int(id1))
    

    应该阅读

        q2='''select id2 from table2 where x=%i and y=%i;''' %(int(id), int(id1))
    

    【讨论】:

      【解决方案2】:

      这应该可行,但它与 SQL 非常非常非常不同。实际上,您这样做是在规避关系数据库的特性。您可能应该使用子查询;使用官方 MySQL 文档了解更多信息。

      【讨论】:

      • 我收到以下错误,TypeError: 'str' object is not callable
      • 显然,将该信息添加到您的原始问题中。
      • 我可以理解,但我有近 1,00,000 条记录,如果我完全使用子查询,则无法完成。所以只有我对每个 id 使用单独的查询。
      • 但是你的代码肯定会更慢,更糟。不要那样做。你为什么要这样做?从架构的角度来看,这很糟糕!
      • 如果我这样使用,每个查询需要 4-5 秒,脚本会在一小时内完成,但如果我这样做,则需要很长时间才能完成。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2020-04-16
      • 1970-01-01
      • 2016-04-24
      • 1970-01-01
      相关资源
      最近更新 更多