Ravindra BagaleCourses & study guides

10. MySQL Part 1: Install, Create, Insert and SELECT

10.9 JOINs

Data vegalya tables madhe aahe – student che naav students madhe, course che naav courses madhe, score enrollments madhe. JOIN te common column var jodto.

  INNER JOIN   only matching rows in both tables
  LEFT JOIN    all rows from the left table + matches (NULL if none)
  RIGHT JOIN   all rows from the right table + matches
  CROSS JOIN   every row with every row (rarely needed)
  SELF JOIN    a table joined with itself
-- INNER: who is enrolled in what, with score
SELECT s.name, c.course_name, e.score
FROM enrollments e
JOIN students s ON s.student_id = e.student_id
JOIN courses  c ON c.course_id  = e.course_id
ORDER BY s.name;

-- LEFT: all students, even those in no course (Raja shows NULL)
SELECT s.name, e.course_id
FROM students s
LEFT JOIN enrollments e ON e.student_id = s.student_id;

-- students who have NO enrollment
SELECT s.name FROM students s
LEFT JOIN enrollments e ON e.student_id = s.student_id
WHERE e.enroll_id IS NULL;

-- RIGHT: all courses, even with no students
SELECT c.course_name, e.student_id
FROM enrollments e
RIGHT JOIN courses c ON c.course_id = e.course_id;

-- SELF JOIN: pairs of students from the same city
SELECT a.name, b.name, a.city
FROM students a JOIN students b ON a.city = b.city AND a.student_id < b.student_id;

MySQL has no FULL OUTER JOIN; combine a LEFT and a RIGHT JOIN with UNION when you need one.

Why this matters for security

UNION lets one query append the results of another – attackers use UNION SELECT username, password FROM users inside a vulnerable query to pull data from a completely different table. Knowing that UNION needs the same number of columns explains the ORDER BY trick from section 10.6.

Ravindra Bagale's Tip

ON condition visarla tar MySQL pratyek row la pratyek row jodto (cross join) aani 10 × 12 = 120 rows yetat – students la vatte data double zala. JOIN lihilyavar nehmi ON aani result chi row count check kara.

Practice task

List each course with the number of students enrolled (include courses with zero), and list students who are enrolled in more than one course.