SELECT MAX MySQL查询 - 异常结果
Here's my MySQL Table
When I carry out the following query : SELECT MAX( Animal_ID ) FROM info_table
I get "9"
Shouldn't it be 10 ?
How can I resolve the error ?
Thanks!
这是我的MySQL表 p>
p>
当我执行以下查询时:SELECT MAX(Animal_ID)FROM info_table p >
我得到“9” p>
不应该是10吗? p>
如何解决错误?
谢谢! p> div>
My guess is that animal_id
is being stored as a character field rather than as a numeric field. If you want the numeric max, try this:
select max(animal_id + 0)
from info_table
When you add two values together in MySQL and one is a character string, then the initial numeric characters (if any) are converted to a number.
Judging by the sample data in your other columns, you have made all your columns of type VarChar
, i.e. text. The "anomalous result" you are seeing is one of the many reasons this is a bad idea.
Sorting a series of strings will generally be done in "alphabetical", or "lexical" order - "b" comes before "z", but not before "aaa". Strings consisting entirely of digits may look like numbers, but they will sort like any other string - so "1" comes before "2", but so does any string beginning with "1", such as "1a", "10", "100". This is generally not what you want.
Rather than working around this and the other problems you will encounter with, e.g. date fields, always set your tables up with correct types on every column.