首页 > 解决方案 > 如何在 MySQL 中使用 JOIN 更新多行?

问题描述

我有 3 张桌子:
进口商:
进口商

类别:
类别

产品类别:
产品类别

当“importer.sku”=“product_categories.product_reference”时,如何将“categories.name”设置为“importer.tag”?

标签: sql

解决方案


你可以尝试这样的事情:

UPDATE categories
SET name = importer.tag
FROM
    categories
    INNER JOIN product_categories ON categories.id = product_categories.category_id
    INNER JOIN importer ON importer.sku = product_categories.product_reference;

请注意,这将更新类别表中的所有可能记录(可以与 product_categories 和导入器表连接)。如果您只需要更新类别中的特定记录,也可以使用 WHERE 子句。

编辑:

不是 categories.name 应该更新,而是 importer.tag...对不起...

UPDATE importer
SET tag = categories.name
FROM
    importer
    INNER JOIN product_categories ON product_categories.product_reference = importer.sku
    INNER JOIN categories ON categories.id = product_categories.category_id;

编辑2:

作为 MS SQL Server 用户,我不知道 MySQL 对 UPDATE 查询使用的语法略有不同。快速浏览 MySQL 文档后,您可以尝试以下查询:

UPDATE
    importer
    INNER JOIN product_categories ON product_categories.product_reference = importer.sku
    INNER JOIN categories ON categories.id = product_categories.category_id
SET
    tag = categories.name;

推荐阅读