【问题标题】:mysql select products which appear in as many lines as quantities have in ordersmysql 选择出现在与订单数量一样多的行中的产品
【发布时间】:2020-11-03 12:55:06
【问题描述】:

有这样一张桌子

+--------+------------+------------+
| 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 |
+--------+------------+

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

【问题讨论】:

    标签: mysql sql select


    【解决方案1】:

    您可以使用递归子查询:

    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;
    

    Here 是一个 dbfiddle。

    【讨论】:

      猜你喜欢
      • 2022-11-27
      • 2014-09-18
      • 2022-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-10-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多