Frage

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';
War es hilfreich?

Lösung

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.

Andere Tipps

use the following code

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

if you need to use the left join then use

    select e.said, s.sname from enroll e left join 
enrool e1 on e1.sid = e.sid left join
student s on s.sid = e.sid left join
course c on c.cno = e.cno
where c.cname = 'computer science' and c.name = 'maths'
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top