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

问题描述 投票:0回答:5

表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)

 );
mysql sql
5个回答
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的数据结构很差。每个国家/地区应该有一行,而不是每个国家/地区只有一列。


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


1
投票

你需要qazxsw poi table和qazxsw poi it to tableAU:

UNPIVOT

但由于mySQL没有JOIN函数,你需要使用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; 手动完成,你应该考虑改变你的表(tableB)结构。

测试它UNPIVOT


0
投票

对所有列执行此操作: -

UNION ALL

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


0
投票

我在MSSQL中完成了它:

here
© www.soinside.com 2019 - 2024. All rights reserved.