【问题标题】:Faster way to do mysql query in python在 python 中进行 mysql 查询的更快方法
【发布时间】:2016-05-10 01:54:30
【问题描述】:

有list1和list2,每个包含1,104,824个值

table1 有 350,000,000 行,3 列:ID、name1、name2

这就是我试图做的:

con = mdb.connect('localhost','user','password','db')
cur = con.cursor()
for i in range(1104824)
    sql ="select count(distinct(a.ID)) from (select name1 ,ID from table1 where name2 <> '"+str(list1[i])+"') as a where a.name1 = '"+str(list2[i])+"'"
    cur.execute(sql)
    data = cur.fetchone()[0]

但它非常非常慢。有没有更快的方法来做这个查询?

【问题讨论】:

  • 张贴表格结构以及您到底想要做什么。肯定有一种方法不涉及 110 万次查询?
  • 如果IDPRIMARY KEY,您可以将COUNT(DISTINCT ID) 更改为COUNT(*)。如果name1,name2 是唯一的,您可能可以摆脱ID

标签: python mysql sql performance


【解决方案1】:

这是您的查询:

select count(distinct a.ID)
from (select name1, ID
      from table1
       where name2 <> '"+str(list1[i])+"'
      ) a
where a.name1 = '"+str(list2[i])+"'";

我建议这样写:

select count(distinct ID)
from table1
where name2 <> '"+str(list1[i])+"' and
      name1 = '"+str(list2[i])+"'";

然后您可以使用table1(name1, name2, id) 上的索引来加快查询速度——所有三列都按此顺序排列。

注意:我会把sql写成:

    sql = """
select count(distinct ID)
from table1
where name2 <> '{0}' and name1 = '{1}'
""".format(str(list1[i]), str(list2[i]))

【讨论】:

    【解决方案2】:

    似乎这也适用于适当的索引:

    select count(distinct id) 
    from table1
    where name2 <> 'Name1'
       and name1 = 'Name2'
    

    尽管考虑使用参数化查询。您的查询很容易受到 sql 注入的影响,并且会因为带有撇号的名称而中断...很多例子,这里有几个:Python MySQL Parameterized Querieshttps://stackoverflow.com/a/1633589/1073631

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多