要选择最大的混合字符串/整数列,您需要使用substring()
函数。语法如下:
SELECT MAX(CAST(SUBSTRING(yourColumnName, 4, length(yourColumnName)-3) AS UNSIGNED)) AS anyVariableName FROM yourTableName;
为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table StringIntMixHighestDemo -> ( -> InvoiceId int NOT NULL AUTO_INCREMENT, -> InvoiceNumber varchar(20), -> PRIMARY KEY(InvoiceId) -> );
现在,您可以使用insert命令在表中插入一些记录。查询如下:
mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV129'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV122'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV1'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV145'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV19'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV134'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV135'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV10'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV100'); mysql> insert into StringIntMixHighestDemo(InvoiceNumber) values('INV121');
使用select语句显示表中的所有记录。查询如下:
mysql> select *from StringIntMixHighestDemo;
以下是输出:
+-----------+---------------+ | InvoiceId | InvoiceNumber | +-----------+---------------+ | 1 | INV129 | | 2 | INV122 | | 3 | INV1 | | 4 | INV145 | | 5 | INV19 | | 6 | INV134 | | 7 | INV135 | | 8 | INV10 | | 9 | INV100 | | 10 | INV121 | +-----------+---------------+ 10 rows in set (0.00 sec)
这是在string / int列中获取最大值的查询。查询如下:
mysql> SELECT MAX(CAST(SUBSTRING(InvoiceNumber, 4, length(InvoiceNumber)-3) AS UNSIGNED)) as HighestValue -> from StringIntMixHighestDemo;
以下是输出:
+--------------+ | HighestValue | +--------------+ | 145 | +--------------+ 1 row in set (0.00 sec)