9

我正在尝试使用 Sqlkata 构建 Sql Query。我能够为一个连接条件构建正确的 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])

请让我知道如何解决此问题

4

2 回答 2

7

根据需要使用OnorWhereX方法,例如

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方法也可以在此上下文中使用

于 2019-05-15T09:14:20.997 回答
0

当您的 on 条件不是恒定的时,您可以定义这个 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));
于 2019-10-04T18:14:35.280 回答