我有一个包含大量条目的现有表,我想为每一行计算一个新列。我只找到了以下解决方案。这可行,但速度很慢,因为它需要扫描表的大部分条目。
我想要的是一种方法:
- 读取一行
- 根据行内容计算新列的值
- 更新到数据库
这样它只会遍历表格一次,并且具有线性复杂度。
cursor.execute("SELECT tweet FROM Table")
row = cursor.fetchone()
while row is not None:
vader = analyser.polarity_scores(row)
sentiment_vader = vader["compound"]
cursor2.execute(
"UPDATE Table SET sentiment_vader = %s WHERE tweet = %s LIMIT 1",
(sentiment_vader, row[0]))
kody.cnx.commit()
row = cursor.fetchone()
最佳答案
我看到的主要性能问题是您不应该提交每行更新,因为这会增加开销。您应该在一段时间结束时或在一批之后提交。
while row is not None:
...
else:
kody.cnx.commit()
此外,如果 tweet
列未建立索引,只需在该列上创建索引,以免在更新期间进行表扫描。
关于python - Python中线性时间动态更新MySQL表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63419111/