使用 'master' table 上的限制和偏移量从具有一对多关系的 2 table 获取数据

getting data from 2 tables with one-to-many relation using limit and offset on a 'master' table

这看起来很简单,所以我有点不好意思问,但问题是:我有 2 个表 - 订单和(订单的)商品。一个订单可以包含一个或多个项目,我想使用 LIMIT 来获取例如前 10 个订单,可能也使用 OFFSET,问题是:如何创建一个查询来做到这一点?例如,如果订单 1 有 2 件商品,订单 2:1 件,订单 3:2 件,订单 4:1 件,我需要前 3 个订单,预期结果为:

  1. 订购 1 件商品 1
  2. 订购 1 件商品 2,
  3. 订购 2 件商品 1,
  4. 订购 3 件商品 1,
  5. 订购 3 件商品 2

使用子查询进行限制和给定

MariaDB [sandbox]> select * from cat_books;
+--------+-------+
| idbook | name  |
+--------+-------+
|      1 | book1 |
|      2 | book2 |
|      3 | book3 |
|      4 | book4 |
+--------+-------+
4 rows in set (0.001 sec)

MariaDB [sandbox]> select * from books_sold;
+---------+--------+--------+
| id_sold | idbook | iduser |
+---------+--------+--------+
|       1 |      1 |      1 |
|       2 |      2 |      1 |
|       3 |      1 |      2 |
|       4 |      1 |      3 |
|       4 |      3 |      5 |
+---------+--------+--------+
5 rows in set (0.001 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> select *
    -> from
    -> (SELECT * FROM CAT_books order by idbook limit 2) cb
    -> join
    -> books_sold bs on bs.idbook = cb.idbook
    -> order by cb.idbook;
+--------+-------+---------+--------+--------+
| idbook | name  | id_sold | idbook | iduser |
+--------+-------+---------+--------+--------+
|      1 | book1 |       3 |      1 |      2 |
|      1 | book1 |       4 |      1 |      3 |
|      1 | book1 |       1 |      1 |      1 |
|      2 | book2 |       2 |      2 |      1 |
+--------+-------+---------+--------+--------+
4 rows in set (0.001 sec)