mysql - 从子实体中为 IN 子句中的每个元素获取 100 行
问题描述
父子关系:OneToMany
Parent - table
+-----+---------+
|id | name |
+-----+---------+
| 1 | name1 |
| 2 | name2 |
| 3 | name3 |
+---------------+
child1 - table
+--+---------+------+
|id|parent_id|name |
+--+---------+------+
| 1| 1 | qwe |
| 2| 1 | asd |
| 3| 1 | dsf |
| 4| 2 | xzc |
+--+---------+------+
表:公司(父)和员工(子)。我想获取所有给定公司的 100 名最近加入的员工以及公司的详细信息。
SELECT c.*, e.*
FROM company c
JOIN (
SELECT *
FROM employee
WHERE company_id IN(2,3,4,5)
ORDER BY joined_at DESC LIMIT 100
) e on e.company_id = c.id where c.id in (2,3,4,5)
上面的查询总共只返回 100 名员工,但我希望IN
子句中提供的每家公司有 100 名员工。
解决方案
您可以使用 Pageable 来获取知道父实体的子实体。请注意,此查询将返回 Child 的分页结果。
/**
* Find Child entities knowing the Parent.
*/
@Query("select child from Parent p inner join p.childs child where p = :parent")
public Page<Child> findBy(@Param("parent") Parent parent, Pageable pageable);
你可以像这样使用它:
Page<Child> findBy = repo.findBy(parent, new PageRequest(page, size));
推荐阅读
- php - 在数据表中按月对数据库表中的数据进行分组
- javascript - 动态创建的 HTML 表格行的 Javascript 日期比较
- nginx - 是否可以设置某种内部 Nginx 服务/部署,可以将调用从一个 GCP 入口重定向到另一个 GCP 入口
- daq-mx - 我如何在这个板上用 C++ 编程?
- guard - Guard 未检测到控制器文件更改
- sql-server - SSRS 表达式 - 仅在数据存在时格式化
- angular - 在浏览器上运行时,本地项目中不显示 p-table 的边框
- javascript - 如何在 React Native 中检测段落中特定单词的样式、超链接
- java - Android Studio:GridLayout 在 v.3.5 中不起作用
- java - Java迭代列表