简体   繁体   English

哪种方法更适合从数据库中检索数据

[英]Which approach is better to retrieve data from a database

I am confused about selecting two approaches. 我对选择两种方法感到困惑。

Scenario 脚本
there are two tables Table 1 and Table 2 respectively. Table 1Table 2分别有两个表。 Table 1 contains user's data for example first name, last name etc Table 1包含用户的数据,例如名字,姓氏等

Table 2 contains cars each user has with its description. Table 2包含每个用户对其描述的汽车。 ie Color , Registration No etc ColorRegistration No

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. 方法1。

Query for all rows in Table 1 and store them all in a list for ex. 查询Table 1所有行,并将它们全部存储在列表中。

then Loop through the list and query it and get data from Table 2 according to user saved in in first step. 然后循环遍历列表并查询它,并根据第一步中保存的用户从Table 2获取数据。

Approach 2 方法2

Query for all rows and while saving that row get its all values from table 2 and save them too. 查询所有行,同时保存该行从table 2获取其所有值并保存它们。

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 如果还有其他更好的主意,请告诉我

Your two approaches will have about the same performance (slow because of N+1 queries). 您的两种方法将具有相同的性能(由于N + 1查询而缓慢)。 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. union-all查询将具有令人惊讶的良好性能,因为sql server将执行“merge union”,其工作方式类似于merge-join。 This pattern also works for multi-level parent-child relationships, although not as well. 此模式也适用于多级父子关系,但不是很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM