【问题标题】:mysql how do i convert row results to column with new column name?mysql 如何将行结果转换为具有新列名的列?
【发布时间】:2020-09-30 04:37:04
【问题描述】:

我有 2 个要加入的 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 和编码来说真的很新)。 谢谢!

【问题讨论】:

  • 你想要实现的是一个支点。你可以在堆栈溢出上找到类似的问题,也可以在 youtube 上搜索一些视频。
  • 是的,我尝试搜索发现了一些类似的问题,但其中大多数都有很多表格/与我的案例有点不同,我真的需要一个像我所拥有的那样简单的案例,这样我就可以有一个更好地了解 mysql 中的枢轴。感谢您的回复!
  • 您使用的是哪个 mysqö 版本
  • 我的mysql版本是8.0.19

标签: mysql sql join pivot window-functions


【解决方案1】:

在 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

【讨论】:

  • 谢谢,它有效!我可以将其用作另一个简单连接查询的子查询来组合两个结果吗?例如查询是“select stock from stock s join product p on p.product_id = s.product_id”。如果是,我将子查询放在哪里?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多