为什么我得到mysql结果列值不匹配

时间:2017-09-16 13:28:18

标签: mysql sql group-by min

msyql查询

SELECT id,student_user_id,MIN(start_time) FROM appoint_course 
WHERE student_user_id IN(
    931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,
    2518,2594,2596,2600,2608,2637,2652,2654
) 
AND course_type=3 and disabled=0  GROUP BY student_user_id;

结果 [查询结果]

+-------+-----------------+-----------------+
| id    | student_user_id | MIN(start_time) |
+-------+-----------------+-----------------+
|  8356 |             931 |      1500351000 |
|  9205 |            2034 |      1501733400 |
|  9246 |            2068 |      1501649100 |
|  9755 |            2111 |      1502943000 |
|  9585 |            2115 |      1502595300 |
| 10820 |            2173 |      1503545700 |
|  9594 |            2181 |      1502852400 |
| 10324 |            2285 |      1502852400 |
| 11204 |            2500 |      1504839600 |
| 11152 |            2507 |      1504064100 |
| 12480 |            2594 |      1505707800 |
| 11521 |            2608 |      1504494000 |
| 11818 |            2652 |      1504753200 |
+-------+-----------------+-----------------+

但正确的开始时间是:

id: 9594
start_time: 1503284400

9594 right start_time是1503284400而不是1502852400.实际上1502852400是9597的记录 我不知道为什么。

1 个答案:

答案 0 :(得分:2)

在任何其他数据库中,您的查询都会返回错误,因为id不在group by中。正确的查询是:

SELECT student_user_id, MIN(start_time)
FROM appoint_course
WHERE student_user_id IN (931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,2518,2594,2596,2600,2608,2637,2652,2654) AND
      course_type = 3 and disabled = 0
GROUP BY student_user_id;

在您的情况下,向MIN(id)添加简单的SELECT可能有效,假设id随着开始时间而增加。

更一般地说,您似乎想要:

SELECT ac.*
FROM appoint_course ac
WHERE ac.student_user_id IN (931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,2518,2594,2596,2600,2608,2637,2652,2654) AND
      ac.course_type = 3 AND ac.disabled = 0 AND
      ac.start_time = (SELECT MIN(ac2.start_time)
                       FROM appoint_course ac2
                       WHERE ac2.student_user_id = ac.student_user_id AND
                             ac2.course_type = ac.course_type AND
                             ac2.disabled = ac.disabled
                      );

不需要GROUP BY

我应该补充说,有一个经常有效的MySQL黑客攻击:

SELECT student_user_id, MIN(start_time),
       SUBSTRING_INDEX(GROUP_CONCAT(id ORDER BY start_time), ',', 1) as id_at_min_start_time
FROM appoint_course
WHERE student_user_id IN (931,2034,2068,2111,2115,2173,2181,2285,2500,2505,2507,2518,2594,2596,2600,2608,2637,2652,2654) AND
      course_type = 3 and disabled = 0
GROUP BY student_user_id;

这使用字符串操作,GROUP_CONCAT()可以溢出内部缓冲区大小。