SQL Join: Display Matching Students and Exam Details

This SQL query demonstrates how to retrieve all students from the 'Student' table and their corresponding exam details from the 'Exam' table using a LEFT JOIN. The query returns all students, even those without associated exams, while including the exam information for those who have taken exams.

Database Schema:

  1. Student (student_id, student_name, student_class, exam_id)
  2. Exam (exam_id, subject_name)

SQL Statement:

Bselect * from student left join exam on student.exam_id = exam.exam_id

Explanation:

  • LEFT JOIN: This type of join returns all rows from the left table (Student) and matching rows from the right table (Exam). If no match is found in the right table, NULL values are returned for the Exam table columns.
  • student.exam_id = exam.exam_id: This condition specifies the join criteria, matching the 'exam_id' column in the Student table to the 'exam_id' column in the Exam table.
  • *select : This selects all columns from both tables.

Result:

The query returns a result set containing all student records with their corresponding exam details. For students who haven't taken any exams, the 'subject_name' column from the Exam table will have NULL values.


原文地址: https://www.cveoy.top/t/topic/oCpu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录