JOIN clause with WHERE

。_饼干妹妹 提交于 2019-12-13 01:28:58

问题


Ive got 3 tables called Course, CourseCatogory, CourseCourseCatagory. CourseCourseCatagory is a junction table. I am trying to select courses that are linked to particular catogory using the junction table. This is my first time using a junction table and JOIN clause, I just don't know how to go about doing it. It would be highly appreciated if there's anything you could do to help me.

 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:


In order to get an understanding of how this works I suggest you start out like:

FROM Course c -- or with CourseCategory

then JOIN the junction table:

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

then join CATEGORY with the junction table:

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

Then add the where clause:

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

I assume that Category is an attribute of CourseCategory (always use a qualifier since it will make the code easier to read and understand). Finally, select from the relation you defined:

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


来源:https://stackoverflow.com/questions/29098795/join-clause-with-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!