Sqlalchemy 简明教程

Parameter-Ordered Updates

原始 SQL 的 UPDATE 查询具有 SET 子句。它由 Update.values() 构造使用原始表对象中给出的列顺序渲染。因此,具有特定列的特定 UPDATE 语句每次都会被渲染相同。由于参数本身作为 Python 词典键传递给 Update.values() 方法,因此没有其他固定的排序可用。

The UPDATE query of raw SQL has SET clause. It is rendered by the update() construct using the column ordering given in the originating Table object. Therefore, a particular UPDATE statement with particular columns will be rendered the same each time. Since the parameters themselves are passed to the Update.values() method as Python dictionary keys, there is no other fixed ordering available.

在某些情况下,SET 子句中呈现的参数顺序很重要。在 MySQL 中,提供列值更新是基于其他列值的更新。

In some cases, the order of parameters rendered in the SET clause are significant. In MySQL, providing updates to column values is based on that of other column values.

以下语句的结果:

Following statement’s result −

UPDATE table1 SET x = y + 10, y = 20

将具有与以下不同的结果:

will have a different result than −

UPDATE table1 SET y = 20, x = y + 10

MySQL 中的 SET 子句以按值方式进行评估,而不是以按行方式进行评估。为此,使用了 preserve_parameter_order 。Python 2 元组列表作为 Update.values() 方法的参数给出:

SET clause in MySQL is evaluated on a per-value basis and not on per-row basis. For this purpose, the preserve_parameter_order is used. Python list of 2-tuples is given as argument to the Update.values() method −

stmt = table1.update(preserve_parameter_order = True).\
   values([(table1.c.y, 20), (table1.c.x, table1.c.y + 10)])

列表对象类似于词典,除了它是按顺序排列的。这确保了 “y” 列的 SET 子句将首先渲染,然后是 “x” 列的 SET 子句。

The List object is similar to dictionary except that it is ordered. This ensures that the “y” column’s SET clause will render first, then the “x” column’s SET clause.