我如何将一个表的1个ID字段加入2个不同的表列

时间:2019-03-06 17:52:27

标签: c# sql-server

我正在制定一个学校管理程序,其中我想将多个表连接到“学生”表,我想将Stidents出生地及其表中的实际地址都使用“城市ID”字段,但我无法弄清楚怎么做。

SELECT Students.StudentID, Students.Name, Students.Birthday, Students.MothersName, Classes.ClassName, Cities.Name, Cities.Name,
PostalCode.PostalCode, Street.StreetName, Students.Number

FROM Students

INNER JOIN Classes ON Students.ClassID = Classes.ClassID
INNER JOIN Cities ON Students.BirthPlaceID = Cities.CityID
INNER JOIN Cities ON Students.CityID = Cities.CityID
INNER JOIN PostalCode ON Students.PostalCodeID = PostalCode.PostalCodeID
INNER JOIN Utca ON Students.StreetID = Streets.StreetID

我已经尝试过这种方法,但是只会导致错误。

1 个答案:

答案 0 :(得分:4)

您为所选表创建别名,然后可以使用2个不同的标识访问同一表。我对您的select语句中的值进行了相同的操作(创建的别名),以识别哪个城市。

SELECT Students.StudentID, Students.Name, Students.Birthday, Students.MothersName, Classes.ClassName, StudentBirthCities.Name as StudentBirthCityName, StudentCity.Name as StudentCityName,
PostalCode.PostalCode, Street.StreetName, Students.Number

FROM Students

INNER JOIN Classes ON Students.ClassID = Classes.ClassID
INNER JOIN Cities StudentBirthCities ON Students.BirthPlaceID = StudentBirthCities.CityID
INNER JOIN Cities StudentCity ON Students.CityID = StudentCity.CityID
INNER JOIN PostalCode ON Students.PostalCodeID = PostalCode.PostalCodeID
INNER JOIN Utca ON Students.StreetID = Streets.StreetID