简体   繁体   English

如何反透视 mysql 中的数据

[英]How to Unpivot Data in mysql

Help Guys, I Have Table帮助伙计们,我有桌子

Table Product:表产品:

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

I want to Select use all of them to become:我想把 Select 全部用成:

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

How Can I Query it?如何查询? thank you谢谢你

One option uses a recursive query, available in MySQL 8.0:一个选项使用递归查询,在 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

Hello hope this will help you.您好希望这会对您有所帮助。

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

Upvote if you find useful.觉得有用就点个赞吧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM