mysql - mysql 选择出现在与订单数量一样多的行中的产品
问题描述
有这样一张桌子
+--------+------------+------------+
| orderID | productID | quantity |
+--------+------------+------------+
| 100 | 10 | 1 |
| 100 | 11 | 1 |
| 101 | 10 | 1 |
| 101 | 11 | 2 |
| 101 | 12 | 1 |
+--------+------------+------------+
是否可以进行查询并获取如下记录?
+--------+------------+
| orderID | productID |
+--------+------------+
| 100 | 10 |
| 100 | 11 |
| 101 | 10 |
| 101 | 11 |
| 101 | 11 |
| 101 | 12 |
+--------+------------+
也就是说,产品出现在与其在订单中的数量一样多的行中。
解决方案
您可以使用递归子查询:
with recursive cte as (
select orderid, productid, 1 as n, quantity
from t
union all
select orderid, productid, n + 1, quantity
from cte
where n < quantity
)
select orderid, productid
from cte;
这是一个 db<>fiddle。
推荐阅读
- xamarin - 在 Xamarin.Forms 中导航或关闭应用程序时如何保存应用程序的状态?
- epplus - Excel 图表中的次轴
- javascript - Nativescript 真实设备日期和时间
- php - 响应式文件管理器,上传图片ckeditor问题
- c# - 使用 R.NET 加载 xlsx 包
- c# - C# NewtonSoft JSON 反序列化泛型属性
- swift - 如何在不使用 UIActivityViewController 的情况下为 Airdrop 共享创建自定义 UI?
- c# - 序列化后的反序列化在 C# 中不起作用
- spring - 我们可以在应用程序中同时使用 CrudRepository 和 ReactiveCrudRepository 吗
- yocto - postinst-intercept 脚本的问题