简体   繁体   English

根据另一个表/列中的值插入一个表/列中的值

[英]Insert value from one table/column based on value from another table/column

I am trying to import a csv, unpivot the data and INSERT INTO product_attribute table.我正在尝试导入 csv,取消透视数据和 INSERT INTO product_attribute表。

I have a table called attributes我有一个名为attributes的表

attribute_id属性ID attribute_name属性名 attribute_value属性值
1 1 colour颜色 black黑色的
2 2 colour颜色 green绿色
3 3 colour颜色 blue蓝色的
4 4 size尺寸 small小的
5 5 size尺寸 medium中等的
6 6 size尺寸 large大的

I have a table called products我有一张名为products的表

product_id product_id sku库存单位 qty数量
1 1 test3测试3 13 13
2 2 test2测试2 17 17
3 3 test1测试1 5 5

I have a table called product_attribute which is linked between both tables above.我有一个名为product_attribute的表,它链接在上面的两个表之间。

product_id product_id attribute_id属性ID

the csv data is as follows which imports into a temp folder called import . csv 数据如下导入到名为import的临时文件夹中。

sku库存单位 colour颜色 size尺寸
test1测试1 black黑色的 small小的
test2测试2 green绿色 large大的
test3测试3 blue蓝色的 medium中等的

so far I have managed to unpivot the csv/table using the following query到目前为止,我已经设法使用以下查询取消透视 csv/表

SELECT sku, 'colour' attribute_name, colour attribute_value
FROM import
UNION ALL
SELECT sku, 'size' attribute_name, size attribute_value
FROM import
UNION ALL

the data then looks like this然后数据看起来像这样

sku库存单位 attribute_name属性名 attribute_value属性值
test1测试1 colour颜色 black黑色的
test2测试2 colour颜色 green绿色
test3测试3 colour颜色 blue蓝色的
test1测试1 size尺寸 small小的
test2测试2 size尺寸 large大的
test3测试3 size尺寸 medium中等的

I need to somehow add a INSERT INTO query with the unpivot query so the product_attribute table looks like the following我需要以某种方式使用 unpivot 查询添加 INSERT INTO 查询,因此product_attribute表如下所示

product_id product_id attribute_id属性ID
3 3 1 1
2 2 2 2
1 1 3 3
3 3 4 4
2 2 6 6
1 1 5 5

I believe a subquery would help me achieve this but I'm not sure how to put it together when the value is based on another column.我相信子查询可以帮助我实现这一目标,但是当值基于另一列时,我不确定如何将其组合在一起。

Any help greatly appreciated thankyou.任何帮助都非常感谢thankyou。

Use your code in a subquery and join it to the two tables using the common columns.在子查询中使用您的代码并使用公共列将其连接到两个表。

INSERT INTO product_attribute(product_id, attribute_id)
    SELECT p.product_id, a.attribute_id
    FROM (
        SELECT sku, 'colour' attribute_name, colour attribute_value
        FROM import
        UNION ALL
        SELECT sku, 'size' attribute_name, size attribute_value
        FROM import
        UNION ALL
    ) as u
    JOIN products p   USING(sku)
    JOIN attributes a USING(attribute_name, attribute_value)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM