如何从包含字母数字字符串的列中获取最大值?

时间:2016-02-05 05:35:26

标签: php mysql casting substr

我有一张表格,其中包含发票和估算编号。发票编号类似于"IN1000","IN1001","IN1002",依此类推。估算编号类似于"ES101","ES102","ES103"。如何获得发票和估计?我也希望它被转换为像1000这样的整数。

我尝试了以下查询:

SELECT Max(CAST (SUBSTR(invoiceNo,3) AS UNSIGNED)) FROM selected_items 
WHERE invoiceNo RLIKE 'IN';

当我运行此查询时,我收到以下错误:

  

#1064 - 您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近'UNSIGNED))FROM selected_items WHERE invoiceNo RLIKE'IN''at   第1行。

我正在使用类似的估算方法:

SELECT Max(CAST (SUBSTR(invoiceNo,3) AS UNSIGNED)) FROM selected_items
WHERE invoiceNo RLIKE 'ES';

如何在一个查询中执行这两项操作?感谢任何帮助。谢谢。

4 个答案:

答案 0 :(得分:2)

根据@FuzzyTree和@TimBiegeleisen的建议,您可以尝试以下查询。

Select (SELECT MAX(CAST(SUBSTR(TRIM(invoiceNo),3) AS UNSIGNED))
FROM selected_items 
WHERE invoiceNo RLIKE 'IN') as maxIN,
(SELECT MAX(CAST(SUBSTR(TRIM(invoiceNo),3) AS UNSIGNED))
FROM selected_items 
WHERE invoiceNo RLIKE 'ES') as maxES;

答案 1 :(得分:1)

我相信您的invoiceNo列有一些额外的字符,即使您使用SUBSTR()后仍然存在。这导致CAST失败,因为仍然存在非数字字符。如果这些额外的字符是空格,那么TRIM()函数可能会派上用场:

SELECT MAX(CAST(SUBSTR(TRIM(invoiceNo),3) AS UNSIGNED))
FROM selected_items 
WHERE invoiceNo RLIKE 'IN'

正如@Tah所指出的,这里有一个链接可以帮助您删除所有字母数字字符,如果涉及到:

MySQL strip non-numeric characters to compare

<强>更新

如果您想在一个查询中获取两个最大值,一种方法是执行您提到的两个查询中的UNION

SELECT 'invoiceMax', MAX(CAST(SUBSTR(TRIM(invoiceNo),3) AS UNSIGNED))
FROM selected_items 
WHERE invoiceNo RLIKE 'IN'
UNION
SELECT 'estimateMax', MAX(CAST(SUBSTR(TRIM(invoiceNo),3) AS UNSIGNED))
FROM selected_items 
WHERE invoiceNo RLIKE 'ES'

答案 2 :(得分:1)

您可以使用条件聚合组合查询:

select
    max(case when invoiceNo rlike 'IN' then (your value here) end) maxIn,
    max(case when invoiceNo like 'ES' then (your value here) end) maxEs
from selected_items
where invoiceNo rlike 'IN'
or invoiceNo like 'ES'

另一种方法是使用子查询。我不确定哪个运行得更快,所以你可能想要测试它们。

select
    (your in query) as maxIn,
    (your en query) as maxEn

答案 3 :(得分:0)

// get max index value   codeinigter
        $res = $this->db->get($table)->result();
        $arr = array();
        foreach ($res as $val) {
            $str = preg_replace('/\D/', '', $val->id);
            $arr[] = $str;
        }
        $or = max($arr) + 1;