Sql Query为以下输出

时间:2015-08-31 01:49:32

标签: sql-server

我有两张桌子:

Table_1: (Name, Street, City)
Table_2: (Name, Teacher_Name)

表1中的列名称包含学生姓名以及教师姓名,而在表格_2列中名称仅包含学生的姓名,而教师姓名包含与学生相对应的教师姓名

所以我的问题是,查找与他们的教师住在同一街道和城市的所有学生的SQl查询是什么。

请提前帮助和谢谢。

2 个答案:

答案 0 :(得分:0)

尝试此查询:

SELECT DISTINCT t1.Name
FROM Table_1 t1 INNER JOIN Table_2 t2
ON t1.Name = t2.Name
INNER JOIN Table_1 t3
ON t3.Name = t2.Teacher_Name
WHERE t1.Street = t3.Street AND t1.City = t3.City

您需要加入两次以达到您想要的效果。第一次连接是将地址表与学生桥接表连接到教师所必需的。然后你需要再次加入以获得这些老师的地址。

答案 1 :(得分:0)

您需要两次加入Table_1。像这样:

SELECT students.Name, teachers.Name
FROM Table_2 AS teacher_student
JOIN Table_1 AS students ON students.Name = teacher_student.Name
JOIN Table_1 AS teachers ON teachers.Name = teacher_student.Teacher_Name
WHERE students.Street = teachers.Street
AND students.City = teachers.City
相关问题