更新表A,其中包含B的信息,其值为列名

时间:2017-12-19 11:51:05

标签: mysql sql

表格A:

Id |sku   |Country       |pricecountry
1   b1     Netherlands     *null* 

表B:

sku    |Germany  |France   |Netherlands
b1     3,88       7,55      6,14

目标是使用sku1更新表A中的列pricecountry。在这种情况下,它应该是6,14

我觉得这样的事情但不知道......

UPDATE tableA as a SET
 a.pricecountry = ( select column(a.country)
                        FROM tableB as b
                        WHERE a.sku = b.sku  and
                        column(a.country)

 );

5 个答案:

答案 0 :(得分:1)

您需要UNPIVOT tableB和JOIN到tableA:

update tableA as A
inner join (
    -- unpivot start
    select sku, 'Germany' as country, Germany as value
    from tableB
    union all
    select sku, 'France' as country, France as value
    from tableB
    union all
    select sku, 'Netherlands' as country, Netherlands as value
    from tableB
    -- unpivot end
) as B
    on A.country = B.country
    and A.sku = B.sku
set A.pricecountry = B.value;

但是由于mySQL没有UNPIVOT功能而您需要使用UNION ALL手动执行,因此您应该考虑更改表( tableB )结构。 / p>

测试here

答案 1 :(得分:1)

UPDATE
    a
INNER JOIN
    b
        ON a.sku = b.sku
SET
    a.price = CASE a.country
                WHEN 'germany'     THEN b.germany
                WHEN 'france'      THEN b.france
                WHEN 'netherlands' THEN b.netherlands END
WHERE
    a.price IS NULL
;

http://sqlfiddle.com/#!9/6485d/1

答案 2 :(得分:0)

为所有列执行此操作: -

UPDATE tableA a 
LEFT OUTER JOIN 
(
    SELECT sku, 'Germany' AS country, Germany AS pricecountry
    FROM tableB
    UNION
    SELECT sku, 'France', France
    FROM tableB
    UNION
    SELECT sku, 'Netherlands', Netherlands
    FROM tableB
) b
ON a.sku = b.sku
AND a.country = b.country
SET a.pricecountry = b.pricecountry

但是,只要添加了新的国家/地区列,您就需要修改它

答案 3 :(得分:0)

最佳性能可能是使用CASE逻辑:

UPDATE tableA a JOIN
       tableB b
       ON a.sku = b.sku
    SET a.pricecountry = (CASE WHEN a.country = 'Netherlands' THEN b.Netherlands
                               WHEN a.country = 'Germany' THEN b.Germany
                               WHEN a.country = 'France' THEN b.France
                          END)
    WHERE a.pricecountry IS NULL;

虽然对TableB进行隐蔽是合理的,但它会阻止在sku上使用索引 - 这就是为什么它对性能不利。

请注意,TableB的数据结构较差。每个国家/地区应该有一行,而不是每个国家/地区有一列。

答案 4 :(得分:0)

我在MSSQL中完成了它:

update a
set a.pricecountry = (case when a.country = 'Netherlands' then b.Netherlands 
                       when a.country = 'Germany' then b.Germany 
                       when a.country = 'France' then b.France end)
from tableA a
inner join tableB b
on a.sku = b.sku
where a.pricecountry is null;