-1

student table

|----------------------|
| student_id | name    |
|------------|---------|
| 1          | Richard |
| 2          | Emily   |
| 3          | Hans    |
|------------|---------|

lecturer table

|--------------------|
| lecturer_id | name |
|-------------|------|
| 1           | John |
| 2           | Mike |
|-------------|------|

classes table

|-----------------------------------------------|
| class_id | lecturer_id | material             |
|----------|-------------|----------------------|
| 1        | 1           | Basic of algorithm   |
| 2        | 1           | Basic of programming |
| 3        | 2           | Database  Essentials |
| 4        | 2           | Basic of SQL         |
|----------|-------------|----------------------|

attendance table

|-----------------------|
| class_id | student_id |
|----------|------------|
| 1        | 1          |
| 1        | 2          |
| 1        | 3          |
| 2        | 1          |
| 2        | 2          |
| 3        | 1          |
| 3        | 2          |
| 3        | 3          |
| 4        | 1          |
| 4        | 2          |
|----------|------------|

how to show classes records (from classes table) that not attended by Hans (student) in MySQL?

desired result :

|-----------------------------------------------|
| class_id | lecturer_id | material             |
|----------|-------------|----------------------|
| 2        | 1           | Basic of programming |
| 4        | 2           | Basic of SQL         |
|----------|-------------|----------------------|
tushar_lokare
  • 461
  • 1
  • 8
  • 22

2 Answers2

1

One approach uses EXISTS:

SELECT c.class_id, c.lecturer_id, c.material
FROM classes c
WHERE NOT EXISTS (SELECT 1 FROM attendance a
                  INNER JOIN student s
                      ON a.student_id = s.student_id
                  WHERE a.class_id = c.class_id AND
                        s.name = 'Hans');
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
1

Using joins -

select c.class_id
from attendance a inner join student s on (a.student_id=s.student_id and s.student_id='Hans')
right outer join classes c on (a.class_id=c.class_id)
where a.class_id is null
Vijiy
  • 1,187
  • 6
  • 21