表中的mysql更新字段来自其他表,第三个表中有链接

时间:2015-01-09 20:10:46

标签: mysql

将产品从prestashop的一个实例迁移到另一个实例,我遇到了一个更改了图像ID(id_image)的问题,但幸运的是同样的产品ID(id_product)。

现在我已经迁移了大部分数据,只缺少表dstshop_image_shop中的字段'cover'。

基本上我希望表dstshop_image_shop包含

(100, 1, 0),
(150, 1, 1),
(180, 1, 1);

表格和一些示例数据如下:

-- Tables for Source Shop
CREATE TABLE srcshop_image (`id_image` int, `id_product` int, `position`int);
CREATE TABLE srcshop_image_shop (`id_image` int, `id_shop` int, `cover` int);

-- Tables for Destination Shop
CREATE TABLE dstshop_image (`id_image` int, `id_product` int, `position`int);
CREATE TABLE dstshop_image_shop (`id_image` int, `id_shop` int, `cover` int);

-- Insert data
INSERT INTO srcshop_image (`id_image`, `id_product`, `position`)
VALUES 
(1, 5, 1),
(2, 5, 2),
(3, 6, 1);

INSERT INTO srcshop_image_shop (`id_image`, `id_shop`, `cover`)
VALUES
(1, 1, 0),
(1, 2, 0),
(2, 1, 1),
(2, 2, 1),
(3, 1, 1),
(3, 2, 1);

INSERT INTO dstshop_image (`id_image`, `id_product`, `position`)
VALUES
(100, 5, 1),
(150, 5, 2),
(180, 6, 1);

INSERT INTO dstshop_image_shop (`id_image`, `id_shop`, `cover`)
VALUES
(100, 1, -1),
(150, 1, -1),
(180, 1, -1);

我认为我的sql技能(或缺乏)让我与这个技能相提并论......

BR MADS

1 个答案:

答案 0 :(得分:0)

如果我理解正确,您需要joins声明中的多个update

update  dstshop_image_shop dis
join dstshop_image di
on dis.id_image = di.id_image
join srcshop_image si
on di.id_product = si.id_product
and di.position = si.position
join srcshop_image_shop sis
on sis.id_image = si.id_image
and dis.id_shop = sis.id_shop
set dis.cover = sis.cover