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

How to get the max value from a column with alphanumeric strings?

我有一个 table,其中包含发票和估算 numbers.The 发票编号类似于 "IN1000","IN1001","IN1002",因此 on.The 估算编号类似于 "ES101","ES102","ES103"。如何我可以获得发票和估价的最大值吗?我也希望它被转换成像 1000 这样的整数。

我试过以下查询:

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

当我 运行 这个查询时,我得到以下错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'UNSIGNED)) FROM selected_items WHERE invoiceNo RLIKE 'IN'' at line 1.

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

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

如何在一个查询中执行这两项操作?任何帮助都是appreciated.Thank你。

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

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

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

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'

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

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

根据@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;
// 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;