简体   繁体   中英

A SQL lookup on two tables;

The database is here: http://sqlfiddle.com/#!9/bf0171

I want to find all students in "Prof.David" class. However, the lookup result is:

Select Student.name from Student, Teacher where Teacher.s_id =Student.id and Teacher.name="Prof. David";
+------+
| name |
+------+
| Tom  |
| John |
| Mary |
| Tom  |
| John |
| Mary |
+------+

I suppose the result should be "Tom" and "John" only. What's the problem?

Without a join criteria between Student and Teacher you'll get a Cartesian product (all records from Student combined with all records from Teacher ).

You probably meant:

SELECT
    Student.name
FROM Student s
JOIN Teacher t
  ON t.s_id = s.id
WHERE Teacher.name="Prof. David";

For new learners of SQL, I would strongly recommend explicitly using using JOIN , LEFT JOIN , etc instead of implicitly joining in the WHERE clause. It will help reduce the number of accidental Cartesian products you execute.

The issue is that you have two tables and you are performing a cartesian join on those tables with your query. Therefore, you are getting 3x2 = 6 rows in your results, where for each teacher you are showing the names of all 3 students. You must join your tables in a logical way based on the foreign key relationships in your schema.

For example:

Select A.field1, B.field2 from A join B on A.id = B.a_id

To see what the problem is, try this:

Select Student.name, Teacher.name from Student, Teacher

You will get a result where every student is combined with every teacher, whether one has anything to do with the other or not. You need to add a condition that checks if the teacher and student are related:

Select Student.name, Teacher.name from Student, Teacher where Teacher.s_id = Student.id

Once you have that you can add more conditions, like listing only the students of a given teacher.

Select Student.name from Student, Teacher where Teacher.s_id = Student.id and Teacher.name=...

You need to add a join clause to the where. I suppose you are trying to select students who have a particular teacher in a particular class. So, for example if you had:

table Student with columns: student_id, name
table Teacher with columns: teacher_id, name
table Class with columns: class_id, class_name, teacher_id
table Class_Assignment with columns class_id, student_id

Then your query would be:

Select Student.name from Student, teacher, class_assignment
   where Student.student_id = class_assignment.student_id
   and Teacher.teacher_id = class_assignment.teacher_id
   and Teacher.name="Prof. David";

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