更快的方式在python中进行mysql查询

时间:2016-05-10 01:54:31

标签: python mysql sql performance

有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]

但它非常慢。有没有更快的方法来进行此查询?

2 个答案:

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

答案 1 :(得分:1)

似乎这样可以与适当的指数一起使用:

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

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

相关问题