我有三张桌子。其中两个是单独的无关表(学生和科目),第三个(条目)是用外键(student_id和subject_id)链接它们的表。
以下是包含记录的所有表格:
生:
+------------+------------+-----------+---------------------+----------------------+
| student_id | first_name | surname | email | reg_date |
+------------+------------+-----------+---------------------+----------------------+
| 1 | Emma | Harvey | emmah@gmail.com | 2012-10-14 11:14:13 |
| 2 | Daniel | ALexander | daniela@hotmail.com | 2014-08-19 08:08:23 |
| 3 | Sarah | Bell | sbell@gmail.com | 1998-07-04 13:16:32 |
+------------+------------+-----------+---------------------+--------------- ------+
主题:
+------------+--------------+------------+----------------+
| subject_id | subject_name | exam_board | level_of_entry |
+------------+--------------+------------+----------------+
| 1 | Art | CCEA | AS |
| 2 | Biology | CCEA | A |
| 3 | Computing | OCR | GCSE |
| 4 | French | CCEA | GCSE |
| 5 | Maths | OCR | AS |
| 6 | Chemistry | CCEA | GCSE |
| 7 | Physics | OCR | AS |
| 8 | RS | CCEA | GCSE |
+------------+--------------+------------+----------------+
输入:
+----------+---------------+---------------+------------+
| entry_id | student_id_fk | subject_id_fk | entry_date |
+----------+---------------+---------------+------------+
| 1 | 1 | 1 | 2012-10-15 |
| 2 | 1 | 4 | 2011-09-21 |
| 3 | 1 | 3 | 2015-08-10 |
| 4 | 2 | 6 | 1992-07-13 |
| 5 | 3 | 7 | 2013-02-12 |
| 6 | 3 | 8 | 2016-01-14 |
+----------+---------------+---------------+------------+
我想知道如何选择学生表中学生的所有 first_name ,其中包含带有OCR exam_board的条目来自 subject 表,使用条目表。 我确定它与连接有关,但是使用哪个连接以及它的一般语法,我都不知道。
我一般都很难解释事情,如果这些事情没有多大意义并且我错过了一些重要的事情,那就很抱歉。如有必要,我很乐意详细说明。
我已经得到了答案,但我正在寻找的是输出结果:
+------------+
| first_name |
+------------+
| Emma |
| Sarah |
+------------+
答案 0 :(得分:2)
您应该在查询中使用INNER JOINS,例如:
SELECT students.first_name
FROM students
INNER JOIN entries
ON entries.student_id_fk = students.student_id
INNER JOIN subjects
ON subjects.subject_id = entries.subject_id_fk
WHERE subjects.exam_board = 'OCR';
此查询将连接匹配键值的表,选择具有exam_board OCR的表并返回学生first_name。