带有 WHERE 的 JOIN 子句

JOIN clause with WHERE

我有 3 个 table 名为 Course、CourseCatogory、CourseCourseCatagory。 CourseCourseCatagory 是一个结 table。我正在尝试 select 使用连接点 table 链接到特定类别的课程。这是我第一次使用联结 table 和 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;
        }

为了了解这是如何工作的,我建议您从以下开始:

FROM Course c -- or with CourseCategory

然后加入路口table:

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

然后加入 CATEGORY 与路口 table:

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 来自您定义的关系:

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