Domanda

Ho un database MySQL con queste due tabelle:

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

Qual è la query per restituire le iniziali e gli ultimi nomi di qualsiasi studente che condividono lo stesso tutore?

Ho provato SELECT intials, lastName FROM Student WHERE tutorId = tutorId ma che restituisce solo i nomi di tutti gli studenti.

È stato utile?

Soluzione

Dovrete unire studenti contro se stesso:

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

Se si desidera emettere le coppie:

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

Per ottenere un elenco di Tutor - Studenti:

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 */

Altri suggerimenti

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

Questo restituirà (non testato, ma dovrebbe) un elenco delle sigle studentesche e cognome raggruppati per tutorId. È questo che vuoi?

Registrazione tabella Student a se stesso

SELECT S1.intials, S1.lastName
FROM Student S1, Student S2 
WHERE S1.tutorId = S2.tutorId 
AND S1.studentId <> S2.studentId

Questa è la query in SQL Server, sono sicuro l'idea è molto vicino a 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

Si dovrà fare una query per ogni singolo tutorId. Pseudo-codice:

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

Se vuoi avere una lista contenente tutti i tutor che in realtà hanno gli studenti, fare un

SELECT tutorId FROM Student GROUP BY tutorId
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top