Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mySQL max() not returning max result

Tags:

mysql

I have trouble trying to retrieve 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.

The query only return JAS9999 as the max result but the max courseid is JAS10000. Am I missing something?

like image 948
Jamie Avatar asked Jul 10 '13 06:07

Jamie


2 Answers

It can't do MAX on numbers embedded in text like this. It makes alphabetical ordering and so JAS9 goes after JAS1. You will have to do max on a substring:

MAX(CAST(SUBSTRING(courseid FROM 4) AS UNSIGNED))
like image 189
sashkello Avatar answered Oct 16 '22 18:10

sashkello


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. I though I would throw in with a php solution.

First get all of the courses that match your like clause in an array.

 $matching = array();
 while ($matching[] = $query->fetchNext()){}

Then

natsort($matching);
$last = end($matching);

Last will contain the last JAS10000 in your case

like image 1
Orangepill Avatar answered Oct 16 '22 18:10

Orangepill