[英]mySQL max() not returning max result
I have trouble trying to retrieve max courseid 我无法尝试检索max courseid
Data: 数据:
coursename courseid
---------- --------
0001_Course JAS9997
0002_Course JAS9998
0003_Course JAS9999
0004_Course JAS10000
Query: 查询:
SELECT max(courseid) FROM tblcourse WHERE courseid LIKE '%JAS%'
The LIKE is to narrow down to courseid that begin with JAS. LIKE将缩小到以JAS开头的标准。
The query only return JAS9999 as the max result but the max courseid is JAS10000. 查询仅返回JAS9999作为最大结果,但最大courseid为JAS10000。 Am I missing something? 我错过了什么吗?
It can't do MAX
on numbers embedded in text like this. 它不能对像这样嵌入文本的数字执行MAX
。 It makes alphabetical ordering and so JAS9 goes after JAS1. 它按字母顺序排序,因此JAS9追求JAS1。 You will have to do max on a substring: 您必须在子字符串上执行max:
MAX(CAST(SUBSTRING(courseid FROM 4) AS UNSIGNED))
A lot of pure sql solutions where provided that should work on the assumption that all of the courses are formated with a three character prefix followed by numbers. 提供的许多纯sql解决方案应该假设所有课程都使用三个字符前缀后跟数字。 I though I would throw in with a php solution. 我虽然会投入PHP解决方案。
First get all of the courses that match your like clause in an array. 首先获得与数组中的like子句匹配的所有课程。
$matching = array();
while ($matching[] = $query->fetchNext()){}
Then 然后
natsort($matching);
$last = end($matching);
Last will contain the last JAS10000 in your case 在您的情况下,最后将包含最后一个JAS10000
Use: 使用:
SELECT MAX(CAST(SUBSTRING(courseid,4) AS UNSIGNED))
FROM tblcourse
WHERE courseid LIKE '%JAS%'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.