简体   繁体   English

从表中选择一个字段具有相同值的行

[英]Selecting rows from a table that have the same value for one field

I have a MySQL database with these two tables: 我有一个带有以下两个表的MySQL数据库:

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. 我尝试了SELECT intials, lastName FROM Student WHERE tutorId = tutorId但这只是返回所有学生的名字。

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

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. 这将返回(未经测试,但应该会)按tutorId分组的学生姓名缩写和姓氏列表。 Is that what you want? 那是你要的吗?

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

这是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

You will have to make a query for every single tutorId. 您将必须为每个单独的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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM