首页 > 解决方案 > 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 |
+--------+------------+

也就是说,产品出现在与其在订单中的数量一样多的行中。

标签: mysqlsqlselect

解决方案


您可以使用递归子查询:

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。


推荐阅读