1

I have a MySQL database with these two tables:

Tutor(tutorId, initials, lastName, email, phone, office)
Student(studentId, initials, lastName, email, tutorId)

What is the query to return the initials and last names of any student who share the same tutor?

I tried SELECT intials, lastName FROM Student WHERE tutorId = tutorId but that just returns the names of all students.

Konerak
  • 39,272
  • 12
  • 98
  • 118
bananamana
  • 485
  • 1
  • 9
  • 19

5 Answers5

4

You'll have to join students against itself:

SELECT s1.initials, s1.lastName
FROM Student s1, Student s2
WHERE s1.studentId <> s2.studentID /* Every student has the same tutor as himself */
AND s1.tutorId = s2.tutorid

If you want to output the pairs:

SELECT s1.initials, s1.lastName, s2.initials, s2.lastName
FROM Student s1, Student s2
WHERE s1.studentId <> s2.studentID /* Every student has the same tutor as himself */
AND s1.tutorId = s2.tutorid

To get a list of Tutor - Students:

SELECT tutorId, GROUP_CONCAT( initials, lastName SEPARATOR ', ') 
FROM `Student` 
GROUP BY tutorId
/* to only show tutors that have more than 1 student: */
/* HAVING COUNT(studentid) > 1 */
Konerak
  • 39,272
  • 12
  • 98
  • 118
1

SELECT Tutor.tutorId, Student.initials, Student.lastName FROM Student INNER JOIN Tutor ON Tutor.tutorId = Student.tutorId GROUP BY tutorId

This will return (not tested, but it should) a list of student initials and last names grouped by tutorId. Is that what you want?

Lucas Moeskops
  • 5,445
  • 3
  • 28
  • 42
1

Join Student table to itself

SELECT S1.intials, S1.lastName
FROM Student S1, Student S2 
WHERE S1.tutorId = S2.tutorId 
AND S1.studentId <> S2.studentId
T33C
  • 4,341
  • 2
  • 20
  • 42
0

this is the query in SQL Server, im sure the idea is very close to mySql:

 select s1.initials,s1.lastname,s2.initials,s2.lastname from students s1 inner join students s2 on s1.tutorid= s2.tutorid and s1.studentid <> s2.studentid
Ali Tarhini
  • 5,278
  • 6
  • 41
  • 66
-1

You will have to make a query for every single tutorId. Pseudo-Code:

for id in tutorIds
    query('SELECT intials, lastName FROM Student WHERE tutorId = '+id )

If you wanna have a list containing all Tutors who actually have students, do a

SELECT tutorId FROM Student GROUP BY tutorId
joni
  • 5,402
  • 1
  • 27
  • 40