MySQL连接返回的行数多于预期的行

时间:2016-11-10 05:56:46

标签: mysql sql

我想要来自三个以上连接的MySQL表的一些记录但是我得到了意外的记录这个查询有什么问题..

1)

admit_card TABLE

class_id|exam_id|subject_id|  exam_date  |exam_time_from|exam_time_to
   1       1         S1      02/12/2016    11:00            02:00    
   2       1         S1      01/12/2016    11:00            02:00    
   2       1         S4      02/12/2016    11:00            02:00    

科目表

section_id_fk|subject_code|subject_name
   1             S1          HINDI
   2             S1          HINDI
   2             S4          COMPUTER

class_details TABLE

class_id_pk|class_name
   1           FIRST
   2           SECOND

section_details TABLE

section_id_pk|class_id_fk|section_name|
   1               1          A
   2               2          A

现在我想从admit_card表中获取记录,该表有三条记录,但这里的联接是强制性的,因为在承认卡中,我有class_id exam_id和subject_id列可以通过他们的高级表。现在我的查询就像:

SELECT class_name,section_name,subject_code,subject_name,ac.exam_date, ac.exam_time_from,ac.exam_time_to 
FROM admit_card ac 
LEFT OUTER JOIN section_details sd ON sd.section_id_pk = ac.class_id 
JOIN class_details cd ON cd.class_id_pk = sd.class_id_fk 
JOIN subjects ON sd.section_id_pk = subjects.section_id_fk 
JOIN admit_card ON admit_card.subject_id = subjects.subject_code;

预期答案

1) FIRST  |A|    S1|  HINDI   |02/12/2016 |  11:00| 02:00
2) SECOND |A|    S1|  HINDI   |01/12/2016 |  11:00| 02:00
3) SECOND |A|    S4|  COMP    |02/12/2016 |  11:00| 12:00

1 个答案:

答案 0 :(得分:0)

您在查询中不应该admit_card两次。要使用不同的表连接列,请在同一ON子句中指定它们。

SELECT class_name,section_name,subject_code,subject_name,ac.exam_date, ac.exam_time_from,ac.exam_time_to 
FROM admit_card ac 
LEFT OUTER JOIN section_details sd ON sd.section_id_pk = ac.class_id 
JOIN class_details cd ON cd.class_id_pk = sd.class_id_fk 
JOIN subjects ON sd.section_id_pk = subjects.section_id_fk AND ac.subject_id = subjects.subject_code

结果:

+------------+--------------+--------------+--------------+---------------------+----------------+--------------+
| class_name | section_name | subject_code | subject_name | exam_date           | exam_time_from | exam_time_to |
+------------+--------------+--------------+--------------+---------------------+----------------+--------------+
| FIRST      | A            | S1           | HINDI        | 2016-02-12 00:00:00 | 11:00          | 02:00        |
| SECOND     | A            | S1           | HINDI        | 2016-01-12 00:00:00 | 11:00          | 02:00        |
| SECOND     | A            | S4           | COMPUTER     | 2016-02-12 00:00:00 | 11:00          | 02:00        |
+------------+--------------+--------------+--------------+---------------------+----------------+--------------+