gpt4 book ai didi

c# - 比较来自不同表的数据并添加到第三个表的最有效方法

转载 作者:行者123 更新时间:2023-11-30 21:43:50 24 4
gpt4 key购买 nike

问题

我有三张 table ,可以说是“第一张 table ”、“第二张 table ”和“第三张 table ”。这三个都有不同的架构,但是,表一和表二有一个匹配列。

表一目前有 50,000 行。表二是 5,000,但会增加。对于表二中的每一行,我需要检查 B 列是否等于表一中的 B 列。如果是,我需要 A 列值。

我做了什么

最初,当表不是那么大时,我有一个嵌套循环来检查值

foreach(DataRow r in TableOne)
{
foreach(DataRow s in TableTwo)
{
if(r.ItemArray[1] == s.ItemArray[1])
doSomethingWith(r.ItemArray[0]);
}
}

但是,我觉得随着表大小的增加,这只会成为一个大的资源问题。

我考虑了以下几点,但不确定是否有更好的方法来进一步证明自己:

SELECT TableOne.ColumnB, TableTwo.ColumnB, TableOne.ColumnA
FROM TableOne
LEFT JOIN ColumnA on TableOne.ColumnB = TableTwo.ColumnB

编辑更清楚地说 - 这是发生在 c# 应用程序中,而不是在服务器端。

最佳答案

For each row in Table Two, I need to check if column B is ever equal to Column B in Table One. If it is I need the Column A value.

SELECT TableOne.ColumnB, TableTwo.ColumnB, TableOne.ColumnA
FROM TableOne
JOIN TableTwo on TableOne.ColumnB = TableTwo.ColumnB
  1. JOIN 将为您提供那些 ColumnBTableOneTableTwo 中都相等的行。
  2. LEFT JOIN 将为您提供上面第 1 项中的所有内容以及与 TableOne 不匹配的所有行。
  3. FULL JOIN 将为您提供上面的 1 和 2 以及与 TableTwo 不匹配的所有行。

你需要上面的数字 1。

如果有很多行,您不希望在应用程序中循环执行此操作,因为要这样做,您需要将所有数据从数据库中提取到应用程序内存中,然后进行过滤。如果 TableOne 中有 500 行,TableTwo 中有 500 行,则需要将 1000 行拉入内存。如果未找到匹配项,则说明您无缘无故地提取了所有这些行。如果您在数据库端执行此操作,它将返回 0 行。

您还可以使用 Linq to SQL 执行此操作:

from one in TableOne
join two in TableTwo on one.ColumnB equals two.ColumnB
select new { OneColumnB = one.ColumnB, TwoColumnB = two.ColumnB, ColumnA = one.ColumnA };

此 Linq to SQL 将为您生成 SQL 查询,连接将发生在 SQL Server 数据库端,因此您的应用程序不会受到惩罚。

关于c# - 比较来自不同表的数据并添加到第三个表的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41371197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com