我有一个包含这两个表的MySQL数据库:
Tutor(tutorId, initials, lastName, email, phone, office)
Student(studentId, initials, lastName, email, tutorId)
返回共享同一导师的任何学生的姓名缩写和姓氏的查询是什么?
我尝试SELECT intials, lastName FROM Student WHERE tutorId = tutorId
,但只返回所有学生的名字。
答案 0 :(得分:4)
你必须加入学生反对自己:
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
如果要输出对:
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
获取导师名单 - 学生:
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 */
答案 1 :(得分:1)
SELECT Tutor.tutorId, Student.initials, Student.lastName FROM Student INNER JOIN Tutor ON Tutor.tutorId = Student.tutorId GROUP BY tutorId
这将返回(未测试,但应该)一个由tutorId分组的学生姓名缩写和姓氏列表。这就是你想要的吗?
答案 2 :(得分:1)
将学生表加入自身
SELECT S1.intials, S1.lastName
FROM Student S1, Student S2
WHERE S1.tutorId = S2.tutorId
AND S1.studentId <> S2.studentId
答案 3 :(得分:0)
这是SQL Server中的查询,我确定这个想法非常接近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
答案 4 :(得分:-1)
您必须对每个tutorId进行查询。伪代码:
for id in tutorIds
query('SELECT intials, lastName FROM Student WHERE tutorId = '+id )
如果您想要一份包含所有实际有学生的导师的清单,请执行
SELECT tutorId FROM Student GROUP BY tutorId