Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在SQLAlchemy中使用批量更新映射来更新具有不同值的多行_Python_Mysql_Sqlalchemy - Fatal编程技术网

Python 在SQLAlchemy中使用批量更新映射来更新具有不同值的多行

Python 在SQLAlchemy中使用批量更新映射来更新具有不同值的多行,python,mysql,sqlalchemy,Python,Mysql,Sqlalchemy,我有两张桌子,一张桌子和一张桌子。我刚刚在Bar表中添加了一个新的列x,它必须使用Foo中的值填充 class Foo(Base): __table__ = 'foo' id = Column(Integer, primary_key=True) x = Column(Integer, nullable=False) class Bar(Base): __table__ = 'bar' id = Column(Integer, primary_key=T

我有两张桌子,一张桌子和一张桌子。我刚刚在Bar表中添加了一个新的列
x
,它必须使用Foo中的值填充

class Foo(Base):
    __table__ = 'foo'
    id = Column(Integer, primary_key=True)
    x = Column(Integer, nullable=False)

class Bar(Base):
    __table__ = 'bar'
    id = Column(Integer, primary_key=True)
    x = Column(Integer, nullable=False)
    foo_id = Column(Integer, ForeignKey('foo.id'), nullable=False)
一种简单的方法是迭代Bar中的所有行,然后逐个更新它们,但这需要很长时间(Foo和Bar中有超过10万行)

现在我想知道这样做是否正确-

mappings = []
for b, foo_x in session.query(Bar, Foo.x).join(Foo, Foo.id==Bar.foo_id):
    info = {'id':b.id, 'x': foo_x}
    mappings.append(info)
session.bulk_update_mappings(Bar, mappings)
关于
bulk\u update\u映射的例子并不多。医生建议

存在且不属于主键的所有键 应用于UPDATE语句的SET子句;主键 必需的值将应用于WHERE子句


因此,在这种情况下,
id
将在
WHERE
子句中使用,然后将使用字典中的
x
值进行更新,对吗?

该方法在用法上是正确的。我唯一想改变的是下面的内容

mappings = []
i = 0

for b, foo_x in session.query(Bar, Foo.x).join(Foo, Foo.id==Bar.foo_id):
    info = {'id':b.id, 'x': foo_x}
    mappings.append(info)
    i = i + 1
    if i % 10000 == 0:
        session.bulk_update_mappings(Bar, mappings)
        session.flush()
        session.commit()
        mappings[:] = []

session.bulk_update_mappings(Bar, mappings)

这将确保内存中不会挂起太多数据,也不会一次对数据库进行太大的插入

@Chris,我想这对你来说是可行的,你只是想确保从方法的角度来看方法是正确的?是的,没错……太好了!我有一百万个数据要更新,sql和后端之间的连接很差。更新过程似乎永远挂起。感谢您提出的拆分数据的建议。有没有办法将where子句指定为主键以外的其他字段?@Mehrdad,我建议在同一个字段上打开一个新查询,并在需要时在此处发布链接。因为问题完全是different@TarunLalwani好建议,我做到了:
mappings = []
i = 0

for b, foo_x in session.query(Bar, Foo.x).join(Foo, Foo.id==Bar.foo_id):
    info = {'id':b.id, 'x': foo_x}
    mappings.append(info)
    i = i + 1
    if i % 10000 == 0:
        session.bulk_update_mappings(Bar, mappings)
        session.flush()
        session.commit()
        mappings[:] = []

session.bulk_update_mappings(Bar, mappings)