如何合并数据库调用的结果?
我有一个网络报告需要返回来自不同地区的多种产品。 简化的查询如下:
Select ProductName, ProductPrice
from Product
where Region in (Region1, Region2, Region 3)
用户从 UI 中选择区域。 结果绑定到数据网格。 可能是多个地区。 但结果会看起来
ProductName, ProductPrice [Region 1] ProductPrice [Region 2] ...
Prod1
Prod2
....
产品与同一地区的产品不一样。 有些在某些地区可能为空。 为了动态绑定到网格,我使用数据表,然后动态添加区域字段的数据列。 最简单的方法是循环每个区域查询的结果,然后按 Product (1, 2, 3...) 合并。它可以工作,但速度很慢,特别是对于超过 2K 的行。 我想知道是否有什么方法可以避免嵌套循环。
I have a web report needs to return multiple products from different regions.
The simplified query will be like:
Select ProductName, ProductPrice
from Product
where Region in (Region1, Region2, Region 3)
The regions are selected by users from UI. The result is bound to a datagrid. It could be multiple regions. But the result will be look like
ProductName, ProductPrice [Region 1] ProductPrice [Region 2] ...
Prod1
Prod2
....
Products are not as same as in the same region. Some might be null in some regions. To dynamically bound to a grid, I am using a DataTable, then dynamically add datacolumn for the region fields. The easiest approach is to loop the result queried by every region, then merge by the Product (1, 2, 3...) It works, but slow, especially for rows more than 2K. I am wondering if any way we can avoid doing nested loop.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您使用的是 SQL Server 吗? 如果是这样,您可以使用
PIVOT
运算符 以该区域为中心。Are you using SQL Server? If so, you can use the
PIVOT
operator to pivot on the region.我想我们可能需要更多关于您正在使用的查询和循环的信息,但是您可以使用 AJAX 吗? 听起来您想让 UI 体验更愉快,并且可以“按需”获取区域信息
I think we may need a little more information about the queries and the loop you are using, but can you use AJAX? Sounds like you want to make the UI experience more enjoyable and could get the information for Regions "on demand"
抱歉,下面的第一个答案是无用的。 如果我理解正确,您可以按产品顺序填充 DataRows,循环结果集:
为每个新的 ProductID 创建一个新的 DataRow,并且每个区域都有一个包含 ProductPrice 值(或没有)的 DataColumn。
该问题缺少基本细节,但总的来说,我建议让 DBMS 处理聚合(如果您使用的是数据库?)。 二维聚合应该很快。
即使这种方法不会如果合适,请尝试最大限度地减少数据源的查询数量。 查询的数量永远不应该依赖于网格列/行数。
Sorry, the first answer below was a dud. If I understand correct, you could fill DataRows in product order, looping the resultset of:
A new DataRow is created for each new productID, and each region has a DataColumn with ProductPrice value (or nothing).
Essential details are missing from the question, but in general I suggest letting the DBMS handle aggregations (if you are using a database?). Two dimensional aggregates should be fast.
Even if this approach would not be suitable, try to minimize the number of queries from your data source. The number of queries should never be dependent on the grid column/row count.