Search code examples
sqljoinself

sql self join problems how to find the duplicates from same table


I am student and

I have such kind of a table structures

student (sid, sname, gender, age, year, gpa)

dept(dname, numphds)

course(cno, cname, dname)

enroll(sid, grade, dname, cno, sectno)

and i want the results for.....

Q-Print the names of students who are taking both a "Computer Sciences" course and a "Maths" course................

I have tried following query but it does not give me throughput..............

select e.sid, s.sname  from 
    enroll e ,enroll e1 ,student s ,course c 
    where s.sid=e.sid, 
         e.cno =c.cno 
      and e.sid=e1.sid 
    and c.cname='computer science' and c.name='maths';

Solution

  • It's been more than 20 years since proper joins were introduced to SQL. FFS use them!

    Try this:

    select s.sid, s.sname
    from student s
    join enroll e on e.sid = s.sid
    join course c on c.cno = e.cno and c.cname='computer science'
    join enroll e1 on e1.sid = s.sid
    join course c1 on c1.cno = e1.cno and c1.name='maths'
    

    Note how you may put non-key conditions in a join condition. Although the query would still work if the course names were in a where clause, putting the conditions in the join clause makes it more obvious where they apply, which improves readability.

    By formatting well and ordering the tables sanely, you can actually read the query and (hopefully) understand it.