简体   繁体   中英

How to apply Self Join

Schema:

Student (snum: integer, sname: char(30), major: char(25), level: char(2), age: integer)

Faculty (fid: integer, fname: char(30), deptid: integer)

Class (cname: char(40), meets_at: char(20), room: char(10), fid: integer | fid REFS Faculty.fid)

Enrolled (snum: integer, cname: char(40) | snum REFS student.snum, cname REFS class.name)

I want to print the level and the age of students for all levels except 'JR'. I know I can apply this query in a simple way. But I want to us e JOINS

My attempt:

select s.levels as Seniority,s.age as Age

from student s

where s.levels not in (

select a.levels

from student a

where a.levels='JR');

This is not giving me expected answer. Am I doing some mistake?

Actually it doesn't make any sense to do sub query or join in this case while you can get it with simple query like.

SELECT level as Seniority, age as Age from student WHERE levels != 'JR'

It should give you desired output.

While I agree a join may be overkill, this looks like homework, in which case you may have been asked to specifically use a join . Here's my attempt:

select distinct levels as Seniority, age as Age
  from student
       natural join
       ( select *
           from student a
          where a.levels != 'JR' );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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