为什么每个字段在 SQL Server 2014 中显示值三次而不是一次



我有以下表格:

  • TB1:Student(学生证、名字、姓氏)
  • TB2:ContactType(联系人类型 ID (pk), Contact_Type)
  • TB3:Contact(联系人 ID (pk), 学生 ID (fk), 联系人信息, 联系人日期, 联系人类型 ID (fk))

我已经在Contact_Type中插入了 3 个值

1    mail
2    email
3    phone

Student表中的 10 个值。我正在尝试完成一项任务,如果Studentid为 2,ContactTypeID为 1,那么在使用 join 语句时,它应该只显示Studentid,应该只显示邮件。当我尝试在 JOIN 语句下面运行时,它在执行下面的连接语句后显示所有 3 列。

学生表:

INSERT INTO Student(FirstName,LastName)
VALUES ('Franklin', 'Babb'), ('Frederick', 'Raub'), ('William', 'Liess'),
('Thomas', 'Santiago'), ('Marian', 'Draudit'),('Aurther', 'Harrington'),
('William', 'Sanson'), ('Bobby', 'McLain'), ('Noble', 'Hughes'),
('Edwin', 'Hart')

ContactType表包含以下信息:

INSERT INTO ContactType(Contact_Type)
VALUES ('Email'), ('Phone'), ('Mail')

Contact表包含以下信息。

INSERT INTO Contact(StudentID, ContactTypeId, ContactInfo, ContactDate)
VALUES (1, 2, 'N/A', '1 Oct 2017'),
(2, 1, 'Student was contacted via email and phone', '5 Oct 2017'),
(3, 3, 'N/A', '15 Oct 2017'),
(4, 1, 'N/A', '25 Oct 2017'),
(5, 3, 'Student was contacted via email and mail', '15 Nov 2017'),
(6, 2, 'Student was contacted via email and phone', '15 Oct 2017'),
(7, 3, 'Student was contacted via mail and phone', '10 Oct 2017'),
(8, 3, 'Student was contacted via email and phone', '2 Oct 2017'),
(9, 2, 'Student was contacted via email and phone', '5 Oct 2017'),
(10, 2, 'N/A', '23 Oct 2017')

联接语句:

SELECT
Student.StudentID,
ContactType.Contact_Type,
Student.LastName + ',' + FirstName AS Student_Name,
Contact.ContactInfo, Contact.ContactDate
FROM 
Student
JOIN 
Contact ON Student.StudentID = Contact.StudentID
JOIN 
ContactType ON Student.StudentID = Contact.StudentID

任何帮助,不胜感激。

提前感谢!

您对两个联接表使用相同的JOIN ON条件,条件应该不同,如下所示:

SELECT
...
FROM Student
JOIN Contact     ON Student.StudentID         = Contact.StudentID
JOIN ContactType ON ContactType.ContactTypeID = Contact.ContactTypeID

最新更新