java - 如何使用加入集合限制结果集
问题描述
我有一个用例,用户可以输入文本,系统会搜索匹配的发票。输入的文本可以匹配发票和发票行上的多个字段。
用户只能根据角色访问所有发票的子集。但这可能是数千张发票的清单。
搜索是通过简单的类似搜索结合通配符来完成的。(查询是用hql写的)
在显示结果时,我们希望将其限制为 50,以不根据用户搜索的内容选择/处理数千个条目。但是,通过我加入的方式,数据库无法强制执行此限制。
我们曾经有过类似的东西(伪代码)
select * from tbl_invoice
join tbl_useraccess .... :userid //a few joins happen here to limit to invoices
//where the user has access to
where number like :input
or name like :input
or id in (select id from InvoiceLine where reference like :input)
limit top 50
这具有非常糟糕的性能,因为搜索是在每个发票行上完成的,而不仅仅是您可以访问的那些,但总是给出正确的 50 行。
我已将其更改为
select * from tbl_invoice invoice
join tbl_useraccess .... :userid
join tbl_invoiceline line on invoice.id = line.invoice_id
where number like :input
or name like :input
or line.reference like :input
limit top 50
性能要好得多(之前的语句只会超时),但限制不起作用,因为一张发票可能有多行。
我们可以从数据库中检索所有结果,将其映射到 java 对象并在 Java 中执行最多 50 个结果,但我担心如果用户检索数以万计的记录,这可能会炸毁我们的内存。
所以总而言之,我正在寻找一种更好的方法来检索固定的结果列表,但也能够在链接的 1-n 实体中进行搜索
解决方案
select * from InvoiceLine line where reference like :input
join tbl_invoice invoice on invoice.id = line.invoice_id
join tbl_useraccess .... :userid
where number like :input
or name like :input
or line.reference like :input
limit top 50
这会将您的发票行数限制为 50。
推荐阅读
- nginx - 带有 nginx 入口的 Rabbitmq
- sql - 带有 TypeORM 的 PostgresQL 我可以从联结表中的 3 个实体实现复合主键吗?
- javascript - Chrome 上的 JavaScript Canvas SVG 线性渐变渲染
- jpa - 如何在 Spring Integration 中将事务范围限制为仅更新 JPA 出站网关(类似于“自动提交”)
- aws-lambda - AWS Lambda - (AccessDeniedException) 调用扫描操作时用户无权执行:dynamodb: Scan
- ios - 水平 UICollectionView 中的刷新控件
- ruby-on-rails - rails 5中唯一性的自定义验证消息
- html - 将 HTML 转换为 netsuite 语言时遇到问题
- sql - SQL Server:更新行需要很长时间
- r - 为不连续的日期调整 r 中 rollapply() 函数中的“宽度”参数