代码之家  ›  专栏  ›  技术社区  ›  Success Man

如何使一条记录的值成为mysql上字段的标题?[副本]

  •  0
  • Success Man  · 技术社区  · 6 年前

    我的问题是这样的:

    SELECT a.number, a.description, b.attribute_code, b.attribute_value 
    FROM items a 
    JOIN attr_maps b ON b.number = a.number WHERE a.number = AB123
    

    enter image description here

    我想得出这样的结果:

    enter image description here

    我该怎么做?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Gordon Linoff    6 年前

    SELECT i.number, i.description,
           MAX(CASE WHEN am.attribute_code = 'brand' then am.attribute_value END) as brand,
           MAX(CASE WHEN am.attribute_code = 'model' then am.attribute_value END) as model,
           MAX(CASE WHEN am.attribute_code = 'category' then am.attribute_value END) as category,
           MAX(CASE WHEN am.attribute_code = 'subcategory' then am.attribute_value END) as subcategory
    FROM items i JOIN
         attr_maps am
         ON am.number = i.number
    WHERE i.number = AB123
    GROUP BY i.number, i.description