简体   繁体   中英

How can I create SQL that does a Left Outer Join and also a count from another table?

I have two entities:

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; }
}

I can join these with a LEFT OUTER JOIN like this:

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

To give:

AdminTestId       Title        CreatedBy
1                 A            NULL
2                 B            99

I also have a table that lists questions in each 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; }

}

How could I modify my SQL to add in the additional table AdminTestQuestions to give the question Count like this:

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

I am using Linq with Entity Framework 6 so a LINQ or SQL solution would be good.

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
            };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM