MySQL查询为什么我的INNER JOIN组日期结果

时间:2012-09-24 06:52:11

标签: mysql date join

我有以下数据库表和列:

students
+------------+-------------------+------------------+
| student_id | student_firstname | student_lastname |
+------------+-------------------+------------------+
|         95 | John              | Doe              |
+------------+-------------------+------------------+

studentcourseplan
+--------+------------+
| cpl_id | student_id |
+--------+------------+
|    209 |         95 |
|    273 |         95 |
+--------+------------+

studentdates
+------------+-------------------+-----------------+
| student_id | student_startdate | student_enddate |
+------------+-------------------+-----------------+
|         95 | 2012-07-02        | 2012-08-17      |
|         95 | 2012-08-20        | 2012-11-16      |
+------------+-------------------+-----------------+

如果我运行此查询...

SELECT 
    scp.cpl_id,
    s.student_id,
    s.student_firstname,
    s.student_lastname,
    sd.student_startdate,
    sd.student_enddate
FROM
    studentcourseplan scp
        INNER JOIN
    students s ON s.student_id = scp.student_id
        INNER JOIN
    studentdates sd ON sd.student_id = s.student_id

...我得到以下输出:

+--------+------------+-------------------+------------------+-------------------+-----------------+
| cpl_id | student_id | student_firstname | student_lastname | student_startdate | student_enddate |
+--------+------------+-------------------+------------------+-------------------+-----------------+
| 209    |         95 | John              | Doe              | 2012-07-02        | 2012-08-17      |
| 273    |         95 | John              | Doe              | 2012-07-02        | 2012-08-17      |
+--------+------------+-------------------+------------------+-------------------+-----------------+

请注意结果中的日期与表studentdates中的值进行比较。他们错了。我希望改为以下输出:

+--------+------------+-------------------+------------------+-------------------+-----------------+
| cpl_id | student_id | student_firstname | student_lastname | student_startdate | student_enddate |
+--------+------------+-------------------+------------------+-------------------+-----------------+
| 209    |         95 | John              | Doe              | 2012-07-02        | 2012-08-17      |
| 273    |         95 | John              | Doe              | 2012-08-20        | 2012-11-16      |
+--------+------------+-------------------+------------------+-------------------+-----------------+

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您需要将cpl_idstudentdates对齐。您可以向studentdates添加一列名为cpl_id&然后相应地更改查询。