【发布时间】:2018-04-28 20:17:42
【问题描述】:
我正在用 C# 编写一个 Web api,并且在我的 get 方法中有一个复杂的 SQL 查询要做。我从一位同事(他现在不在这里或无法访问)那里收到了一个 SQL 文件,其中包含以下内容:
FROM orsrg ors WITH (NOLOCK)
INNER JOIN orkrg ork WITH (NOLOCK) ON ork.ordernr = ors.ordernr
LEFT JOIN cicmpy c1 WITH (NOLOCK) ON ork.debnr = c1.debnr
LEFT JOIN cicmpy c2 WITH (NOLOCK) ON ork.fakdebnr = c2.debnr
LEFT JOIN cicmpy c3 WITH (NOLOCK) ON ork.verzdebnr = c3.debnr
FULL JOIN humres h with (nolock) on h.res_id = ork.represent_id
到目前为止,这是我为此拥有的 C# 代码:
// This "using" is used to make the tables in the SQL query run as "WITH (NOLOCK)" ! (IsolationLevel.ReadUncommitted)
using (var txn = new TransactionScope(
TransactionScopeOption.Required,
new TransactionOptions
{
IsolationLevel = IsolationLevel.ReadUncommitted
}
))
{
// Your LINQ to SQL query goes here
var query = (from ors in _context.Orsrg
join ork in _context.Orkrg on ors.Ordernr equals ork.Ordernr
join c1 in _context.Cicmpy.DefaultIfEmpty() on ork.Debnr equals c1.Debnr
join c2 in _context.Cicmpy.DefaultIfEmpty() on ork.Fakdebnr equals c2.Debnr
join c3 in _context.Cicmpy.DefaultIfEmpty() on ork.Verzdebnr equals c3.Debnr
// FULL JOIN MUST COME HERE
);
}
如您所见,我已经对表 ors 和 ork 进行了内部连接,然后在表 c1、c2、c3 上进行了三个左连接(尽管都来自 Cicmpy)。所以剩下的就是完全连接。
我在 stackoverflow 上也找到了以下代码(这不是我的代码):
var firstNames = new[]
{
new { ID = 1, Name = "John" },
new { ID = 2, Name = "Sue" },
};
var lastNames = new[]
{
new { ID = 1, Name = "Doe" },
new { ID = 3, Name = "Smith" },
};
var leftOuterJoin = from first in firstNames
join last in lastNames
on first.ID equals last.ID
into temp
from last in temp.DefaultIfEmpty(new { first.ID, Name = default(string) })
select new
{
first.ID,
FirstName = first.Name,
LastName = last.Name,
};
var rightOuterJoin = from last in lastNames
join first in firstNames
on last.ID equals first.ID
into temp
from first in temp.DefaultIfEmpty(new { last.ID, Name = default(string) })
select new
{
last.ID,
FirstName = first.Name,
LastName = last.Name,
};
var fullOuterJoin = leftOuterJoin.Union(rightOuterJoin);
该代码通过将其分成两半进行完全外连接,一旦他进行左外连接,一次右外连接,然后将它们放在一个变量中。
我不知道如何在我原来的 C# 代码中做到这一点,现在它说
// FULL JOIN MUST COME HERE
这些 SQL 查询比在学校要难很多...
【问题讨论】:
-
首先这不是 MySQL,它是 SQL Server,所以你必须更改标签。你想让我做什么?将该查询转换为 LINQ 查询?
-
let关键字在这里非常有用。let p = (some query) -
tutorialspoint.com/sql/sql-full-joins.htm 显然 union all 也一样
-
编辑了标签,我需要的是c#linq to sql中的SQL查询,特别是如何与内连接和3个左连接一起进行完全连接。
标签: c# sql-server linq join