0

I have two table. For example : Teacher(name, classCode) and ClassSession(classCode, session, name).

and the query is : find all teacher that teaches subject A.

For example:

Teacher
peter 1
Mary 2

ClassSession
1 summer database
1 spring database
...

And I query like this :

select * from teacher,ClassSession
where Teacher.classCode = ClassSession.classCode

And the result will be:

Peter 1 summer database
Peter 1 spring database

the result is duplicate attribute teacher name, because one subject can teach in multisessions. So, my question is : How can I query to avoid this duplicate. the result should only be Peter name.

Peter 1
Werner Henze
  • 16,404
  • 12
  • 44
  • 69
hqt
  • 29,632
  • 51
  • 171
  • 250

2 Answers2

1

Try this:

select distinct tch.*
from teacher tch ,ClassSession cls
where Tch.classCode = Cls.classCode

However, I would recommend the following:

Use proper join syntax..

select distinct tch.*
from teacher tch 
join ClassSession cls on Tch.classCode = Cls.classCode

Also, not sure why you ever need to join two tables, since you are not pulling any information from the ClassCode table. If you need the second table for the class name, do the following:

select distinct tch.*,cls.Name
from teacher tch 
join ClassSession cls on Tch.classCode = Cls.classCode
Sparky
  • 14,967
  • 2
  • 31
  • 45
1

In my understanding this:

find all teacher that teaches subject A    

the query should be this:

select * from teacher,ClassSession
where Teacher.classCode = ClassSession.classCode  
and ClassSession.classCode = 'A';

because all your original query is returning is everywhere the teacher.classCode matches any given classCode.

Now in terms of removing the duplicate Peter entries that one becomes a bit more difficult, so what you most likely want to do is this:

    select ClassSession.* from teacher,ClassSession
    where Teacher.classCode = ClassSession.classCode  
    and ClassSession.classCode = 'A'  
    and Teacher.name = 'Peter';  

now what this does is stops querying the teacher table because you already know whom you are looking for and you supply that as part of the where clause.

After OP update

    select distinct teacher.* from teacher,ClassSession
    where Teacher.classCode = ClassSession.classCode  
    and ClassSession.classCode = 'A'; 
Woot4Moo
  • 23,987
  • 16
  • 94
  • 151