猿问

Codeigniter MySQL select max using varchar type

我想从我的代码标记器模型中的以下 varchar 类型列中选择最大auto_no


+------------+

|  auto_no   |

+------------+

| 2020-00821 |

| 2020-00822 |

| 2020-00823 |

| 2020-00824 |

| 2020-00825 |

+------------+ 

在此示例中,值为 825。我尝试了以下选项


public function generate_auto_no($count = 1, $start = 00000, $digits = 5)

    {

        $query = $this->db->get('letter_letter');

        $this->db->select("MAX(CAST(SUBSTRING_INDEX(auto_no, '-', -1) AS UNSIGNED)) AS auto_no", FALSE);        

        $count = ($query->num_rows() > 0) ? $query->row()->auto_no + 1 : 0;

        $result = array();

        for ($n = $start; $n <= $start + $count; $n++) {

            $result[] = str_pad($n, $digits, "0", STR_PAD_LEFT);

        }

        return date("Y").'-' . end($result);

    }

但没有得到预期的价值。任何人都可以帮忙吗?


临摹微笑
浏览 156回答 3
3回答

沧海一幻觉

我瘦你可以只选择最大字符串:$this->db->select_max("auto_no");$query = $this->db->get('letter_letter');if ($query->num_rows() > 0) {&nbsp; &nbsp; $last_auto_no = $query->row()->auto_no;&nbsp; &nbsp; $no = intval(explode('-', $last_auto_no)[1]) + 1;&nbsp; &nbsp; $auto_no = date("Y").'-' . str_pad($no, $digits, "0", STR_PAD_LEFT);} else {&nbsp; &nbsp; $auto_no = (date("Y").'-' . str_pad(0, $digits, "0", STR_PAD_LEFT));}return $auto_no

翻翻过去那场雪

一种选择是使用自定义查询:$this->db->query("&nbsp;SELECT&nbsp;MAX(&nbsp;CAST(&nbsp;SUBSTR(auto_no,INSTR(auto_no,'-')+1,LENGTH(auto_no))&nbsp;AS&nbsp;SIGNED)&nbsp;)&nbsp;FROM&nbsp;tab&nbsp;");包括MySQL DB的众所周知的字符串运算符。

幕布斯7119047

可以通过使用值,然后提取最后 5 个字符的数量来检索 naximum 值:MAX()varcharselect&nbsp;right(max(in_num),&nbsp;5)&nbsp;+&nbsp;0 from&nbsp;tablename观看演示。结果:825
随时随地看视频慕课网APP
我要回答