2

连接有问题。

我有一张桌子叫subjects

subno   subname
30006   Math
31445   Science
31567   Business

我还有一张叫enrollment

subno sno   
30009 980008
4134  988880

ETC..

如何列出学生 9800007 的科目编号和科目名称?

4

2 回答 2

3

If you want to return zero rows for students without an enrolment, use a LEFT [OUTER] JOIN, eg:

SELECT e.sno, s.subno, s.subname
FROM enrollment e LEFT OUTER JOIN subjects s ON s.subno = e.subno
WHERE e.sno=988880;

To return no rows for students without enrolments, use an INNER JOIN:

SELECT e.sno, s.subno, s.subname
FROM enrollment e INNER JOIN subjects s ON s.subno = e.subno
WHERE e.sno=988880;

Note that join order is important for outer joins (RIGHT [OUTER] JOIN and LEFT [OUTER] JOIN - the OUTER keyword is optional) but not for INNER JOIN. For that reason, @swetha's answer has a problem: the join order is reversed if you're looking for information about a student.

See this SQLFiddle

于 2013-04-25T05:24:14.623 回答
1

尝试这个

 select * 
 from subjects s 
   left join enrollment e on s.subno = e.subno  
 where sno=9800007 
于 2013-04-25T05:17:35.857 回答