【问题标题】:How to Unpivot Data in mysql如何在 mysql 中取消透视数据
【发布时间】:2020-07-24 13:44:15
【问题描述】:

帮助伙计们, 我有桌子

餐桌产品:

| id | product | quantity |
| 1  | tea     | 2        |
| 2  | juice   | 3        |

我要选择全部使用成为:

| id | product |
| 1  | tea     |
| 1  | tea     |
| 2  | juice   |
| 2  | juice   |
| 2  | juice   |

如何查询?谢谢你

【问题讨论】:

  • 考虑处理应用代码中数据显示的问题

标签: mysql sql database recursive-query unpivot


【解决方案1】:

一个选项使用递归查询,在 MySQL 8.0 中可用:

with recursive cte as (
    select id, product, quantity from mytable
    union all
    select id, product, quantity - 1 from cte where quantity > 1
)
select id, product from cte

【讨论】:

  • 你的意思是我需要另一张桌子吗? cmiiw
  • @TondoKtbffh:不,只需将 mytable 替换为您的表的实际名称即可。
【解决方案2】:

您好,希望对您有所帮助。

SELECT a.id , a.product , a.quantity 
FROM Product a 
cross join 
(select * from seq_1_to_10000) b 
where a.quantity >= b.seq

如果觉得有用,请点赞。

【讨论】:

    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-06
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多