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

Why i get mysql result column value dismatch

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对start_time是1503284400不是1502852400.In其实1502852400是记录9597 不知道为什么。

在任何其他数据库中,您的查询将 return 出错,因为 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;

在您的情况下,向 SELECT 添加一个简单的 MIN(id) 可能会起作用,假设 ids 随着开始时间的增加而增加。

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

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() 会溢出内部缓冲区大小。