MySQL 使用嵌套查询插入或更新

MySQL insert or update with nested query

我有一个查询需要在 table 中插入值,如果键已经存在则更新它们。

此请求如下:

INSERT INTO table1(`id`, `day`, `quantity`, `residue`)
      SELECT
          id,
          SUBDATE(NOW(), 1) as day,
          (
             A SUB QUERY 
          ) as qte,
          (
             ANOTHER SUB QUERY
          ) as r
FROM table2
ON DUPLICATE KEY UPDATE 
  quantity=qte, 
  residue=r;

此请求导致错误 Unknown column 'qte' in 'field list' 我错过了什么?

你想要VALUES():

ON DUPLICATE KEY UPDATE 
    quantity = VALUES(quantity), 
    residue = VALUES(residue)

这是如何工作的explained in the documentation

In assignment value expressions in the ON DUPLICATE KEY UPDATE clause, you can use the VALUES(col_name) function to refer to column values from the INSERT portion .