mysql如何将行结果转换为具有新列名的列?

pbgvytdp  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(586)

我有两个mysql表,我想加入,但我想列'类别'的结果是在一个新的列,而不是行。
第一个看起来像这样

table name = petshop.product
|==========================|
|product_id | product_name |
|==========================|
|     1     | Dog & Cat Toy|
|     2     | Dog Food     |
|==========================|

第二个看起来像这样

table name = petshop.category
|============================|
|category_id | category_name |
|============================| 
|      1     |Dog            |
|      2     |Food           |
|      3     |Toy            |
|      4     |Cat            | 
|============================|

我还有一个表来存储这样的关系

table name = petshop.product_category
=================================
|pc_id| product_id | category_id|
|===============================|
|  1  |     1      |      1     |
|  2  |     1      |      3     |
|  3  |     1      |      4     |
|  4  |     2      |      1     |
|  5  |     2      |      2     |
|===============================|

如何输出结果如下所示的表

|====================================================|
|product_name|  category1  |  category2 |  category3 |
|====================================================|
|Dog&Cat Toy |  Dog        | Toy        | Cat        |
|Dog Food    |  Dog        | Food       | NULL       |
|====================================================|

我读过关于pivot的文章,但我不能完全理解它(说实话,对mysql和一般的编码来说都是新手)。谢谢您!

roejwanj

roejwanj1#

在mysql 8.0中,可以通过连接来解决这个问题, row_number() 要枚举每个产品的类别,以及条件聚合以透视结果集,请执行以下操作:

select 
    product_name,
    max(case when rn = 1 then category_name end) category1,
    max(case when rn = 2 then category_name end) category2,
    max(case when rn = 3 then category_name end) category3
from (
    select 
        p.product_id,
        p.product_name,
        c.category_name,
        row_number() over(partition by p.product_id order by c.category_id) rn
    from product p
    inner join product_category pc on pc.product_id = p.product_id
    inner join category c on c.category_id = pc.category_id
) t
group by product_id, product_name

相关问题