使用SQL联接显示正确的结果

时间:2018-03-27 00:36:28

标签: sql sql-server

首先,我是SQL(T-SQL)的新手,我很感激这方面的指导。 我有3个表,其值创建如下。

CREATE Table StudentProject
(ID int identity (1,1) PRIMARY KEY,
ProjectName Varchar (30),
DueDate Date)


CREATE Table StudentName 
(ID int identity (1,1) PRIMARY KEY,
StudentName Varchar (30))

CREATE Table StudentWork
(ID int identity (1,1) PRIMARY KEY,
ProjectID int,
StudentID int)

Insert Into StudentProject values 
('Omega','1/2/2005'),('KingOmega','1/3/2000'),('Beast','1/6/2007'), 
('DeltaMovie','3/7/2008')

Insert into StudentName values
('Roger'),('John'),('James'),('Juliet'),('William')

Insert into StudentWork values
(1,1),(1,2),(2,2),(2,3),(3,3),(3,4),(1,3)

目标是产生以下结果,但似乎我不能或我确定我做错了。

SQL_Outcom

SQL_Outcome

请帮忙。

3 个答案:

答案 0 :(得分:3)

SELECT StudentProject.ProjectName, StudentName.StudentName
FROM StudentWork 
INNER JOIN StudentProject ON StudentProject.ID = StudentWork.ProjectID
INNER JOIN StudentName ON StudentName.ID = StudentWork.StudentID

您有3个表,尝试识别"主表",然后将它们连接到其他表,加入后,您将可以访问其列。

Hello World:)

<强>更新

为了确认Roger始终使用id 1和StudentName表中的所有其他学生,您需要使用SET IDENTITY_INSERT来保证行的排序。

而不是:

Insert into StudentName values
('Roger'),('John'),('James'),('Juliet'),('William')

这样做:

SET IDENTITY_INSERT StudentName ON

Insert into StudentName values
(1,'Roger'),(2,'John'),(3,'James'),(4,'Juliet'),(5,'William')

SET IDENTITY_INSERT StudentName OFF

答案 1 :(得分:2)

您需要使用内部联接,以便匹配彼此相关的记录:

Select  p.ProjectName, s.StudentName  from StudentName  s
    Inner join Studentwork sw on sw.studentid = s.Id
    inner join StudentProject p on p.ID= sw.ProjectId
    Order by P.ProjectName desc

答案 2 :(得分:2)

您需要inner join

试试这个:

select s.StudentName,p.ProjectName from StudentName s
inner join StudentProject sp on sp.id= sw.ProjectId
inner join StudentWork sw on sw.studentid = s.id;