从第三个表中检索数据

时间:2013-06-12 11:53:09

标签: sql sql-server relation

这个问题令人恼火,因为我还没有在sql中使用中间表。但我现在很忙,所以无论如何我都选择了。

我希望将这些sql代码组合在一起,这样我就可以在同一个转发器中从“老师”以及“团队”和“级别”中检索数据。

我从“老师”表中通过中间表“teacher_team”中的FK_teacher获取一个名称,该名称通过FK_team与我的团队表相关

是否有可能将这些结合起来,以便我可以通过一个中继器提取它?

// Team <-> level relation

SELECT 
team.team_id as team_id,
level.level as level,
FROM team
INNER JOIN level ON level.level_id = team.team_FK_level
WHERE team.team_FK_type = @id


// Team <-> Team_Teacher <-> Teacher relation

SELECT teacher.teacher_name as name 
FROM teacher WHERE teacher.teacher_id 
IN (
SELECT teacher_team.FK_teacher
FROM teacher_team 
INNER JOIN team ON team.team_id = teacher_team.FK_team
WHERE team.team_FK_type = @id
) 

*编辑* 根据Ravi Singh的答案得到这段代码。我遇到了另一个问题。 如果在teacher_teams(当然)中有两位与之相关的教师,我的转发器将输出两次排队。有没有办法在没有在转发器内部转发器的情况下合并这些?

SELECT 
team.team_id as team_id,
level.level as level,
teacher_team.FK_teacher,
teacher.teacher_name as teacher
FROM team
INNER JOIN level ON level.level_id = team.team_FK_level
LEFT JOIN teacher_team on teacher_team.FK_hold = team.team_id
LEFT JOIN teacheron teacher.teacher_id = teacher_team.FK_teacher
WHERE team.team_FK_type = @id

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT 
teacher.teacher_name as name 
,team.team_id as team_id
,level.level as level
FROM teacher 
inner join teacher_team on teacher.teacher_id =teacher_team.FK_teacher
INNER JOIN team ON team.team_id = teacher_team.FK_team
INNER JOIN level ON level.level_id = team.team_FK_level
WHERE team.team_FK_type = @id

更新 这应该有助于您更新的问题:

with demo_cte as(
SELECT 
teacher.teacher_name as name 
,team.team_id as team_id
,level.level as level
FROM teacher 
inner join teacher_team on teacher.teacher_id =teacher_team.FK_teacher
INNER JOIN team ON team.team_id = teacher_team.FK_team
INNER JOIN level ON level.level_id = team.team_FK_level
WHERE team.team_FK_type = @id
)


select distinct t1.team_id,
  t1.level, 
  STUFF(
         (SELECT ', ' + t2.name
          FROM demo_cte t2
          where t1.team_id = t2.team_id
            and t1.level = t2.level

          FOR XML PATH (''))
          , 1, 1, '')  AS name
from demo_cte t1;