繁体   English   中英

在具有联接的查询中使用查询的多个结果

[英]use multiple results of a query within the query with joins

我的数据库中有一些表,其中三个主要表,另一个具有多对多关系。

1. Student (student_id, student_name)
2. Sport (sport_id, sport_name)
3. Departm (depart_id, depart_name) 
4. Sch (sch_id, sch_name)
5. StudSport(relationid, studendid, sportid, departid, schid)

我想做的是,例如,当我知道ID时,根据关系检索部门的名称。 我可以得到这样的ID:

SELECT departid, schid from studsport 
inner join Student on student_id = studentid 
inner join Sport on sport_id = sportid
where student_id = 1 and sport_id=2

但是我想从相应的表中获取部门和Sch的名称,但我不知道该怎么做。

这样的东西???

select sch.sch_nam, departm.depart_name,

-- what you have already --

Left outer Join StudSport on Student.student_id = Studsport.studentid and Sport.sport_id = StudSport.sportid
left outer Join Sch on StudSport.schid = Sch.sch_id
left outer join Departm on studsport.depart_id = studsport.departid

这是未经测试的,因此,提琴使给出答案变得容易得多。

编辑-我误读了您的原始查询-在下注开始下雨之前-立即修复。

您应该使用LEFT OUTER和INNER联接的方式是数据的含义(再次,小提琴通常会很有用),但是根据我的猜测,这只是联接的一部分:

select *

from studsport
join student on studsport.studentid = student.student_id
join sport on studsport.sportid = sport.sport_id
left outer Join Sch on StudSport.schid = Sch.sch_id
left outer join Departm on studsport.depart_id = studsport.departid

where student_id = 1 and sport_id=2

由于您没有从Student或Sport中选择任何内容,因此可以删除相应的内部联接。

SELECT d.depart_name, sch.sch_name FROM StudSport s
INNER JOIN Sch sch ON s.schid = sch.sch_id
INNER JOIN Departm d ON s.departid = d.depart_id
WHERE s.studendid = 1 AND s.sportid = 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM