简体   繁体   English

ADO.NET SQL查询联接?

[英]ADO.NET SQL Query Join?

I am writing a little test app which connects to a SQL Server database which has 2 tables in it. 我正在编写一个连接到具有2个表的SQL Server数据库的小测试应用程序。 Table 1 is a list of data with a non unique key which points to multiple rows in table 2. At the moment what I do is traverse each record in Table 1 and then get the relevant records from Table 2 with a separate query. 表1是具有非唯一键的数据列表,该键指向表2中的多行。目前,我要做的是遍历表1中的每个记录,然后使用单独的查询从表2中获取相关记录。 Table 2 has over 26 million records in it and this process takes a very long time. 表2中有超过2600万条记录,此过程需要很长时间。 The data in Table 1 could have just a few hundred records in it or anything up to about 1 million. 表1中的数据可能只有几百条记录,也可能只有100万条记录。

Is there a way of speeding up this data access? 有没有一种加快这种数据访问的方法? Perhaps using a table join to get all the data in one query? 也许使用表联接在一个查询中获取所有数据? Or anything else? 还是其他?

Sorry I cannot post the database tables or current code as I am under NDA as it is very sensitive data. 抱歉,我无法发布数据库表或当前代码,因为我是NDA,因为它是非常敏感的数据。 The current code is sort of irrelevant here anyway as I am looking for a totally new (and better) way of doing this. 无论如何,当前的代码在这里都是无关紧要的,因为我正在寻找一种全新的(更好的)方法。

Please note I am using ADO within .NET with C#. 请注意,我正在使用C#在.NET中使用ADO。

EDIT: I am okay doing the JOIN query but more asking if this will be more efficient with ADO? 编辑:我可以做联接查询,但更多的问这是否将与ADO更有效? I know it would be more efficient in general but not sure if ADO can handle this. 我知道一般来说效率会更高,但不确定ADO是否可以处理此问题。 Also looking for some example C# code to do this. 还寻找一些示例C#代码来执行此操作。 Thanks. 谢谢。

You can get all the data in one go with a JOIN like this: 您可以使用JOIN一次性获得所有数据:

SELECT t1.NonUniqueKey, t2.*
FROM Table1 t1
    JOIN Table2 t2 ON t1.NonUniqueKey = t2.NonUniqueKey

You'll want to consider putting an index on NonUniqueKey, but this should be better for you than executing n queries, one per row in Table1 您可能要考虑在NonUniqueKey上放置一个索引,但这对您来说比执行n个查询(Table1中的每行一个查询)更好

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

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