我正在尝试通过使用Sqlkata来构建Sql查询。我能够为一个连接条件构建正确的sql查询,但是对于And Condition我正面临问题
var empDeptQuery = new Query("employee");
empDeptQuery.Select("employee.Name", "dept.Deptname");
empDeptQuery.Join("dept", join => join.On("employee.deptid", "dept.deptid"));
SqlResult empDeptSqlKataQuery = compiler.Compile(empDeptQuery);
最终查询-empDeptSqlKataQuery.Sql是
SELECT [employee].[Name], [dept].[Deptname] FROM [employee]
INNER JOIN [dept] ON ([employee].[deptid] = [dept].[deptid])
我想像以下方式那样在join子句中添加更多条件。
SELECT [employee].[Name], [dept].[Deptname] FROM [employee]
INNER JOIN [dept] ON ([employee].[deptid] = [dept].[deptid] And [employee].[empdeptname]=[dept].[departmentName])
我已经尝试过了,但是没有达到我的期望
var empDeptQuery = new Query("employee");
empDeptQuery.Select("employee.Name", "dept.Deptname");
empDeptQuery.Join("dept", join => join.On("employee.deptid", "dept.deptid"));
empDeptQuery.Join(empDeptQuery, join => join.On("employee.empdeptname", "dept.departmentName"));
SqlResult empDeptSqlKataQuery = compiler.Compile(empDeptQuery);
使用上述方法的最终SQL查询:
SELECT [employee].[Name], [dept].[Deptname] FROM [employee]
INNER JOIN [dept] ON ([employee].[deptid] = [dept].[deptid])
INNER JOIN (SELECT [employee].[Name], [dept].[Deptname] FROM [employee]
INNER JOIN [dept] ON ([employee].[deptid] = [dept].[deptid])) ON ([employee].[empdeptname] = [dept].[departmentName])
请让我知道如何解决此问题
答案 0 :(得分:0)
根据需要使用On
或WhereX
方法,例如
new Query("employee")
.Select("employee.Name", "dept.Deptname")
.Join("dept",
j => j.On("employee.deptid", "dept.deptid")
.On("employee.countryid", "dept.countryid")
)
请注意,On
只是WhereColumns
方法的别名,因此所有WhereX
方法在此上下文中都可以使用
答案 1 :(得分:0)
当您的接通条件不是恒定的时,您只需定义此ext方法
internal static class SqlKataExt
{
internal static Join On(this Join j, List<Tuple<string, string>> onConditions, string op = "=")
{
foreach (var o in onConditions)
{
j = j.On(o.Item1, o.Item2);
}
return j;
}
}
其中onConditions
代表配对条件的列表。
例如:{{"t1.col1", "t2.col1"}, {"t1.col2", "t2.col2"}...}
然后像这样使用它
SqlKata.Query query = new SqlKata.Query();
query = query.LeftJoin(inner, j => j.On(onConditions));