我有一张table
| ID|朋友|
| --|--|
| 1 |NULL|
| 2 |NULL|
| 3 |[1,4]|
| 4 |[1、2]|
我的任务是建立用户朋友的所有联系
如果friends为NULL,那么我们遍历所有其他ID,并查找谁拥有这个ID作为好友。
ID为1的ID为NULL。我们使用该脚本来查找谁的好友中有1。ID编号为3和4。因此,记住3和4,在您完成所有-保存此数组到第一个。每行依此类推。
所以,我必须确定哪些ID是我正在寻找的ID的朋友。确定后,我将拥有一个数组,与我写入的数组相同,而不是NULL。
所以我应该得到:
| ID|朋友|
| --|--|
| 1 |[3、4]|
| 2 | 4 |
| 3 |[1,4]|
| 4 |[1、2]|
但是如果它不是NULL,您仍然需要遍历所有用户并记录是否有任何更改
ID 4有一个这样的列表[1,2]。但是ID 3有用户4([1,4])。所以我在现有列表中添加4。
这就是它是什么:[1,2]
以下是它应该是:[1,2,3]
(重要的是,你必须这样做.sort())
我做了什么
for row in cursor:
id = row[0]
friends = row[1]
print(id, friends)
if friends == None:
new_friends = []
for row in cursor:
fr_id = row[0]
str_fr_friends = row[1]
if str_fr_friends != None:
fr_id = row[0]
str_fr_friends = row[1]
fr_friends = json.loads(str_fr_friends)
# print(fr_id, fr_friends)
if fr_id not in new_friends:
if id in fr_friends:
new_friends.append(fr_id)
print(id, new_friends)
# print(fr_id, fr_friends)
new_friends = json.dumps(new_friends)
if new_friends != []:
cursor.execute("UPDATE Users SET friends = ? WHERE id = ?", (new_friends, id))
字符串
我决定从friends为NULL的情况开始处理。
我的问题是代码只编辑第一行。如果我再次运行它,它会转到第二行。
我添加了一个部分来处理friends不为NULL的情况,但它使事情变得更糟。
问:我怎样才能让脚本编辑每一行?
我的数据库有850,000,000行,所以我是逐行阅读它的。也许我应该使用不同的阅读方法,但绝对不可能将它完全加载到文件中
1条答案
按热度按时间laximzn51#
由于大量的记录和表范围的聚合操作,使用查询可能是最有效的,而不是通过Python将大多数/所有记录加载到内存中。查询扫描每行,并执行两个操作:
1.如果
friends
是null
,则它查找表中所有其他在其friends
数组中具有null
友元id
的id
,并聚合结果1.否则,
friends
数组将通过union all
与其friends
数组中包含原始id
的所有其他id
合并字符串