如何创建执行左外连接的SQL以及另一个表中的计数?

时间:2014-10-03 03:22:44

标签: sql sql-server linq

我有两个实体:

public class AdminTest
{
    public AdminTest()
    {
        this.AdminTestQuestions = new List<AdminTestQuestion>();
        this.UserTests = new List<UserTest>();
    }
    public int AdminTestId { get; set; }
    public string Title { get; set; }
    public virtual ICollection<AdminTestQuestion> AdminTestQuestions { get; set; }
    public virtual ICollection<UserTest> UserTests { get; set; }
}

public UserTest()
    {
        this.UserTestQuestions = new List<UserTestQuestion>();
    }

    public int AdminTestId { get; set; }
    public int CreatedBy { get; set; }
    public int UserTestId { get; set; }
    public virtual AdminTest AdminTest { get; set; }
}

我可以通过这样的LEFT OUTER JOIN加入这些:

SELECT AdminTest.AdminTestId, AdminTest.Title, UserTest.CreatedBy FROM AdminTest
LEFT OUTER JOIN UserTest
ON AdminTest.AdminTestId = UserTest.AdminTestId

给予:

AdminTestId       Title        CreatedBy
1                 A            NULL
2                 B            99

我还有一个表格,列出了每个adminTest中的问题:

public partial class AdminTestQuestion
{
    public int AdminTestQuestionId { get; set; }
    public int AdminTestId { get; set; }
    public System.Guid QuestionUId { get; set; }
    public virtual AdminTest AdminTest { get; set; }

}

我如何修改我的SQL以在附加表AdminTestQuestions中添加以提出问题计数如下:

AdminTestId       Title        Questions  CreatedBy
1                 A            10         NULL
2                 B            20         99

我正在使用Linq和Entity Framework 6,因此LINQ或SQL解决方案会很好。

1 个答案:

答案 0 :(得分:1)

SQL

SELECT
    AdminTest.AdminTestId,
    AdminTest.Title,
    COUNT(AdminTestQuestion.AdminTestQuestionId) Questions,
    UserTest.CreatedBy
FROM
    AdminTest LEFT OUTER JOIN UserTest
ON
    AdminTest.AdminTestId = UserTest.AdminTestId JOIN AdminTestQuestion
ON
    AdminTest.AdminTestId = AdminTestQuestion.AdminTestId
GROUP BY
    AdminTest.AdminTestId, AdminTest.Title, UserTest.CreatedBy

LINQ

var query = from at in db.AdminTests
            join ut in db.UserTests
            on at.AdminTestId equals ut.AdminTestId into at_uts
            from at_ut in at_uts.DefaultIfEmpty()
            select new
            {
                at.AdminTestId,
                at.Title,
                Questions = at.AdminTestQuestions.Count(),
                at_ut.CreatedBy
            };