哪种方法更好地从数据库检索数据

发布于 2024-11-09 00:30:02 字数 547 浏览 0 评论 0原文

我对选择两种方法感到困惑。

场景
有两个表,分别是Table 1Table 2表 1 包含用户的数据,例如名字、姓氏等。

表 2 包含每个用户拥有的汽车及其描述。即颜色注册号

现在,如果我想获得所有用户的所有信息,那么什么方法最好在最短的时间内完成?

方法 1.

查询表 1 中的所有行并将它们全部存储在列表中。

然后循环遍历列表并根据第一步中保存的用户从表2中获取数据。

方法 2

查询所有行,并在保存该行时从表 2 获取其所有值并保存它们。

如果我想到系统进程,那么我认为它可能是相同的,因为两种方法中要处理的记录数量相同。

如果有其他更好的想法请告诉我

I am confused about selecting two approaches.

Scenario
there are two tables Table 1 and Table 2 respectively. Table 1 contains user's data for example first name, last name etc

Table 2 contains cars each user has with its description. i.e Color, Registration No etc

Now if I want to have all the information of all users then what approach is best to be completed in minimum time?

Approach 1.

Query for all rows in Table 1 and store them all in a list for ex.

then Loop through the list and query it and get data from Table 2 according to user saved in in first step.

Approach 2

Query for all rows and while saving that row get its all values from table 2 and save them too.

If I think of system processes then I think it might be the same because there are same no of records to be processed in both approaches.

If there is any other better idea please let me know

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

迟月 2024-11-16 00:30:02

您的两种方法将具有大致相同的性能(由于 N+1 查询而缓慢)。像这样执行单个查询会更快:

select *
from T1
left join T2 on ...
order by T1.PrimaryKey

您的客户端应用程序可以解释结果并将所有数据包含在单个查询中。另一种选择是:

select *, 1 as Tag
from T1
union all
select *, 2 as Tag
from T2
order by T1.PrimaryKey, Tag

这只是伪代码,但您可以使其工作。

union-all 查询将具有令人惊讶的良好性能,因为 sql server 将执行“合并并”,其工作方式类似于合并连接。这种模式也适用于多层次的父子关系,尽管效果不太好。

Your two approaches will have about the same performance (slow because of N+1 queries). It would be faster to do a single query like this:

select *
from T1
left join T2 on ...
order by T1.PrimaryKey

Your client app can them interpret the results and have all data in a single query. An alternative would be:

select *, 1 as Tag
from T1
union all
select *, 2 as Tag
from T2
order by T1.PrimaryKey, Tag

This is just pseudo code but you could make it work.

The union-all query will have surprisingly good performance because sql server will do a "merge union" which works like a merge-join. This pattern also works for multi-level parent-child relationships, although not as well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文