基于mysql上的映射表的列名

时间:2016-02-05 16:35:33

标签: mysql sql mapping

我是mysql的新手。我有2张桌子。

表1:product_details

manufacturerID| sku | image1                   | image2                   | image3
--------------------------------------------------------------------------------------------------
     123      |  1  | image1-sku1-filename.jpg | image2-sku1-filename.jpg | image3-sku1-filename.jpg    
     123      |  2  | image1-sku2-filename.jpg | image2-sku2-filename.jpg | image3-sku2-filename.jpg    
     123      |  3  | image1-sku3-filename.jpg | image2-sku3-filename.jpg | image3-sku3-filename.jpg
     456      | 10  | image1-sku10-filename.jpg| image2-sku10-filename.jpg| image3-sku10-filename.jpg
     456      | 20  | image1-sku20-filename.jpg| image2-sku20-filename.jpg| image3-sku20-filename.jpg

表2:image_mapping

manufacturerID | image_column | image_type
-------------------------------------------
    123        | image3       | master
    123        | image1       | extra
    123        | image2       | extra
    456        | image3       | master

我需要一个SELECT查询,它根据manufacturerID和每个sku将所有产品(sku)映射到产品图像(将替换表2中的图像列名称)。

表3:product_images

manufacturerID | sku | product_image            | image_type
--------------------------------------------------------------
    123        |  1  | image3-sku1-filename.jpg | master
    123        |  1  | image1-sku1-filename.jpg | extra
    123        |  1  | image2-sku1-filename.jpg | extra
    123        |  2  | image3-sku2-filename.jpg | master
    123        |  2  | image1-sku2-filename.jpg | extra
    123        |  2  | image2-sku2-filename.jpg | extra
    123        |  3  | image3-sku3-filename.jpg | master
    123        |  3  | image1-sku3-filename.jpg | extra
    123        |  3  | image2-sku3-filename.jpg | extra
    456        | 10  | image3-sku10-filename.jpg| master    
    456        | 20  | image3-sku20-filename.jpg| master

1 个答案:

答案 0 :(得分:1)

以下内容适用于我的数据:

SELECT pd.manufacturerID, sku, 
       CASE WHEN im.image_column = 'image1' THEN pd.image1 
            WHEN im.image_column = 'image2' THEN pd.image2
            WHEN im.image_column = 'image3' THEN pd.image3 
            END AS prod_image, im.image_type
FROM product_details pd
JOIN image_mapping im
ON pd.manufacturerID = im.manufacturerID;

SQLFiddle:http://sqlfiddle.com/#!9/76fc1/3/0