mySql 中包含多个表和 Order By 和 LIMIT 的更新语句

Update statement with multiple tables and Order By and LIMIT in mySql

当我尝试 运行 一个包含多个 table 的更新语句以及 mySql 中的 Order By 和 LIMIT 时,如下所示,

CREATE TRIGGER `Percent` AFTER INSERT ON `tbl_products`
FOR EACH ROW BEGIN
UPDATE
tbl_product_rate t1,
  ( SELECT tbl_products.id, (rate * number) AS prt
    FROM tbl_products left join tbl_products_rate on tbl_products.id = tbl_products_rate.id GROUP BY id
  ) t2
SET
  t1.option = t2.prt
WHERE
  t1.id = t2.id ORDER BY t1.id LIMIT 1;
END


我有如下错误,

[Last executed query: EXECUTE mdb2_statement_mysql_142db9909b0277f32407f2a5d4da240eabf37dd822 USING @0]
[Native code: 1221]
[Native message: Incorrect usage of UPDATE and ORDER BY]


谁能告诉我如何修复上面的更新语句,以便 order by 和 limit 可以用于更新语句 有多个 tables?

p.s。如果我 运行 没有 ORDER BY 和 LIMIT 的更新语句,它将更新 table 中存在的所有行而不会出现错误。

如 mysql 更新语句手册所述:

You can also perform UPDATE operations covering multiple tables. However, you cannot use ORDER BY or LIMIT with a multiple-table UPDATE.

这意味着您需要将多个 table 更新语句转换为单个 table 更新语句才能执行操作。

根据查询,在我看来,您想要 tbl_products table.

中的单个值 (rate * number)

我不清楚选择标准,因为您是在用于加入的字段上进行排序,这意味着该字段对于所有记录都具有完全相同的值,并且您没有对分组依据使用任何聚合函数。这意味着您的子查询违反了 sql 标准,并且在 mysql 中只有 运行,因为您没有设置唯一的完整组 by sql 模式。您也没有引用正在更新的记录,因此不知道此查询与当前记录有何关系。

因此,我无法建议如何将连接重写为子查询。但这就是您需要做的:将您的连接重写为子查询。