WHERE的JOIN子句

时间:2015-03-17 12:13:35

标签: c# sql visual-studio ms-access oledb

我有3个名为Course,CourseCatogory,CourseCourseCatagory的表。 CourseCourseCatagory是一个交汇表。我正在尝试使用联结表选择与特定catogory相关联的课程。这是我第一次使用联结表和JOIN子句,我只是不知道如何去做。如果有什么可以帮助我的话,我们将非常感激。

 public static courseDetails getSelectedCatogory(string Category)
        {
              courseDetails details = new courseDetails();

            using (OleDbConnection connection = getConnection())
            {
                string query = "SELECT CourseName, Description FROM CourseCourseCategory WHERE Category = @Category JOIN Course ON Course.ID = CourseCourseCategory.CourseID " +
                    "JOIN CourseCategory ON CourseCategory.ID = CourseCourseCategory.CourseCategoryID";

                OleDbCommand command = new OleDbCommand(query, connection);
                OleDbParameter pram = new OleDbParameter("@CourseCategory", CourseCategory);
                command.Parameters.Add(pram);
                connection.Open();

                OleDbDataReader reader = command.ExecuteReader();

                while (reader.Read())
                {

                  courseDetails d = new courseDetails();

                  d.CourseName = reader["CourseName"].ToString();
                  d.Description = reader["Description"].ToString();

                    details = d;
                }



            }

            return details;
        }

1 个答案:

答案 0 :(得分:1)

为了了解这是如何工作的,我建议你从:

开始
FROM Course c -- or with CourseCategory

然后加入联结表:

FROM Course c
JOIN CourseCourseCategory cc
    ON c.ID = cc.CourseID

然后将CATEGORY与联结表连接:

FROM Course c
JOIN CourseCourseCategory ccc
    ON c.ID = cc.CourseID
JOIN CourseCategory cc
    ON cc.ID = ccc.CourseCategoryID

然后添加where子句:

FROM Course c
JOIN CourseCourseCategory ccc
    ON c.ID = cc.CourseID
JOIN CourseCategory cc
    ON cc.ID = ccc.CourseCategoryID
WHERE cc.Category = @Category

我假设Category是CourseCategory的一个属性(总是使用限定符,因为它会使代码更容易阅读和理解)。最后,从您定义的关系中选择:

SELECT c.CourseName, c.Description
FROM Course c
JOIN CourseCourseCategory ccc
    ON c.ID = cc.CourseID
JOIN CourseCategory cc
    ON cc.ID = ccc.CourseCategoryID
WHERE cc.Category = @Category