Subsonic 2.2 SqlQuery with Inner Join和Where

时间:2010-08-10 13:43:58

标签: c# .net sql subsonic

我正在尝试使用SqlQuery功能将以下SQL转换为Subsonic语法:

SELECT DISTINCT * FROM FamilyMemberTeamRole FMTR 
INNER JOIN TeamRole TR ON FMTR.TeamRoleId = TR.TeamRoleId
INNER JOIN Team T ON T.TeamId = TR.TeamId
LEFT JOIN FamilyMemberClassHistory FMCH ON FMCH.FamilyMemberClassHistoryId = FMTR.FamilyMemberClassHistoryId
LEFT JOIN CBSClass CG ON CG.CBSClassGroupId = FMCH.CBSClassGroupId
LEFT JOIN CBSClassSession CS ON CG.CBSClassGroupId = CS.CBSClassGroupId 
AND (CS.ClassStartDate <= FMTR.EndDate or FMTR.EndDate IS NULL)
AND (CS.IsHistory = 0 OR CS.IsHistory = NULL)
WHERE FMTR.FamilyMemberId = @FamilyMemberId

我提出了这个,但是我在最后一个左连接的语法出了问题,因为我不知道如何比较SqlQuery中的值和它们自己。

SqlQuery sql = new Select().From(FamilyMemberTeamRole.Schema.TableName)
.InnerJoin(TeamRole.TeamRoleIdColumn, FamilyMemberTeamRole.TeamRoleIdColumn)
.InnerJoin(Team.TeamIdColumn, TeamRole.TeamIdColumn)
.LeftOuterJoin(FamilyMemberClassHistory.FamilyMemberClassHistoryIdColumn, FamilyMemberTeamRole.FamilyMemberClassHistoryIdColumn)
.LeftOuterJoin(CBSClass.CBSClassGroupIdColumn, FamilyMemberClassHistory.CBSClassGroupIdColumn)
.LeftOuterJoin(CBSClassSession.CBSClassGroupIdColumn, CBSClass.CBSClassGroupIdColumn)
.AndExpression(CBSClassSession.Columns.ClassStartDate).IsLessThanOrEqualTo(FamilyMemberTeamRole.Columns.EndDate)
.Or(FamilyMemberTeamRole.Columns.EndDate).IsNull().CloseExpression()
.AndExpression(CBSClassSession.Columns.IsHistory).IsEqualTo(false)
.Or(CBSClassSession.Columns.IsHistory).IsNull().CloseExpression()
.Where(FamilyMemberTeamRole.Columns.FamilyMemberId).IsEqualTo(this.FamilyMemberId)
.Distinct();

1 个答案:

答案 0 :(得分:1)

您始终可以使用BuildSqlStatement()方法检查亚音速为您生成的查询:

SqlQuery query = DB.Select().From<Product>();
String output = query.BuildSqlStatemtent();

但我想我知道问题所在:据我所知,SubSonic2 Join方法不支持连接多个列:subsonic 2 join on multiple columns

所以你基本上有两种选择。

a)做一个“逗号加入”

SELECT * FROM table1
INNER JOIN table2 ON table1.id = table2.table1_id

与下面的查询相同,但更具可读性

SELECT * FROM table1, table2
WHERE table1.id = table2.table1_id

至少对于mysql来说是正确的

编辑:在我的问题中(但已经忘记了),这对亚音速不起作用

http://www.mysqlperformanceblog.com/2010/04/14/is-there-a-performance-difference-between-join-and-where/

b)使用InlineQuery作为亚音速后门来执行普通的sql。

    private class Process
    {
        public Int64 Id { get; set; }
        public string User { get; set; }
        public string Host { get; set; }
        public string Db { get; set; }
        public string Command { get; set; }
        public string State { get; set; }
        public string Info { get; set; }
    }

    var result = DB.Query().ExecuteTypedList<Process>("SHOW FULL PROCESSLIST");