Python中的SQLite表处理

ccrfmcuu  于 7个月前  发布在  SQLite
关注(0)|答案(1)|浏览(42)

我有一张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行,所以我是逐行阅读它的。也许我应该使用不同的阅读方法,但绝对不可能将它完全加载到文件中

laximzn5

laximzn51#

由于大量的记录和表范围的聚合操作,使用查询可能是最有效的,而不是通过Python将大多数/所有记录加载到内存中。查询扫描每行,并执行两个操作:
1.如果friendsnull,则它查找表中所有其他在其friends数组中具有null友元idid,并聚合结果
1.否则,friends数组将通过union all与其friends数组中包含原始id的所有其他id合并

select p.id, case when p.friends is null then (select json_group_array(p1.id) 
       from people p1 where exists (select 1 from json_each(p1.friends) v where v.value = p.id)) 
    else (select json_group_array(v1.pid) from (select p1.id pid from people p1 
          where exists (select 1 from json_each(p1.friends) v where v.value = p.id)
          union all
          select v.value pid from json_each(p.friends) v) v1) end
from people p

字符串

相关问题