如何使用联接基于另一个表在mysql中更新多个值

时间:2019-03-22 04:53:23

标签: mysql sql

我有两个表产品和过滤器。我的产品表如下:-

id    name    color_id    size_id    composition_id
 1    Test      Black     60x60 CM       Cotton
 2    Test2     Red       60X90 CM      Acryllic

我的过滤器表如下:-

id    filter_name
 1      Black
 2      Red
 22     60x60 CM 
 23     60X90 CM
 61     Cotton
 62     Acryllic

我的预期输出如下:-

id    name    color_id    size_id    composition_id
 1    Test       1            22           61
 2    Test2      2            23           62

我已经尝试过以下仅对color_id有效的查询。查询如下:-

UPDATE products
INNER JOIN filters ON products.color_id = filters.filter_name
SET products.color_id = filters.id

我要在一个更新语句中更新所有'color_id,size_id,composition_id'。可能是我们需要使用案例陈述。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

执行此操作的一种方法是使用一组相关的子查询,每个需要查询的列对应一个。我们使用COALESCE,以便如果找不到该值,则保留先前的值:

UPDATE products p
  SET color_id = COALESCE((SELECT id FROM filters WHERE filter_name = p.color_id), color_id),
      size_id = COALESCE((SELECT id FROM filters WHERE filter_name = p.size_id), size_id),
      composition_id = COALESCE((SELECT id FROM filters WHERE filter_name = p.composition_id), composition_id)

然后您可以SELECT * FROM products

id  name    color_id    size_id composition_id
1   Test    1           22      61
2   Test2   2           23      62

Demo on dbfiddle

您还可以通过UPDATE ... JOIN查询获得相同的结果,这可能会更有效:

UPDATE products p
LEFT JOIN filters f1 ON f1.filter_name = p.color_id
LEFT JOIN filters f2 ON f2.filter_name = p.size_id
LEFT JOIN filters f3 ON f3.filter_name = p.composition_id
SET color_id = COALESCE(f1.id, color_id),
    size_id = COALESCE(f2.id, size_id),
    composition_id = COALESCE(f3.id, composition_id)

Demo on dbfiddle