首页 > 解决方案 > 如何使用加入集合限制结果集

问题描述

我有一个用例,用户可以输入文本,系统会搜索匹配的发票。输入的文本可以匹配发票和发票行上的多个字段。

用户只能根据角色访问所有发票的子集。但这可能是数千张发票的清单。

搜索是通过简单的类似搜索结合通配符来完成的。(查询是用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 实体中进行搜索

标签: javahibernatespring-bootjpaquery-optimization

解决方案


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。


推荐阅读