MySQL更新从同一个表中选择

时间:2017-09-17 14:24:40

标签: mysql sql-update

如何使用此查询更新同一表的列:

update products 
set (related_product_id) = 
(
select GROUP_CONCAT(id) from products
INNER JOIN products_cross on products_cross.product_upc = products.upc
WHERE products_cross.related_product_upc = 2631695
)

之前的产品表:

id   |   upc   |   related_product_id  |
3721 | 2631695 |                       |
4566 | 37262   |                       |
3723 | 173615  |                       |
3724 | 216571  |                       |

产品表之后:

id   |   upc   |   related_product_id  |
3721 | 2631695 |  4566,3723,3724       |
4566 | 37262   |                       |
3723 | 173615  |                       |
3724 | 216571  |                       |

产品交叉表:

product_upc | related_product_upc |   
37262       | 2631695             |  
173615      | 2631695             |
216571      | 2631695             |        

2 个答案:

答案 0 :(得分:0)

可能会像下面那样

update products p1
join (
   select c.related_product_upc ,GROUP_CONCAT(product_upc) related_products
   from products p
   join products_cross c on c.related_product_upc = p.upc
   where c.related_product_upc = 2631695
   group by c.related_product_upc 
) t on( t.related_product_upc = p1.upc)
set p1.related_product_id = t.related_products;

DEMO

注意:将相关产品存储为逗号分隔值是一种糟糕的设计,而您可以创建一个新表并关联您的产品,以便将每个关系存储为一行

related_products

product_id related_product_id
3721        4566
3721        3723
3721        3724

答案 1 :(得分:0)

另一种方法如下例所示:

使用mysql局部变量

SELECT 
  @product_id_list_comma_separated := GROUP_CONCAT(table1.id) 
FROM
  products AS table1 
  INNER JOIN products_cross 
    ON products_cross.product_upc = table1.upc ;

UPDATE products AS table2 SET table2.related_product_id = @product_id_list_comma_separated;