gpt4 book ai didi

php - Codeigniter MySQL使用varchar类型值选择最大值

转载 作者:行者123 更新时间:2023-11-29 09:24:06 25 4
gpt4 key购买 nike

我想从我的 codeigniter 模型中的以下 varchar 类型列中选择 max 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);
}

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

最佳答案

我认为你可以选择最大字符串:

$this->db->select_max("auto_no");
$query = $this->db->get('letter_letter');
if ($query->num_rows() > 0) {
$last_auto_no = $query->row()->auto_no;
$no = intval(explode('-', $last_auto_no)[1]) + 1;
$auto_no = date("Y").'-' . str_pad($no, $digits, "0", STR_PAD_LEFT);
} else {
$auto_no = (date("Y").'-' . str_pad(0, $digits, "0", STR_PAD_LEFT));
}
return $auto_no

关于php - Codeigniter MySQL使用varchar类型值选择最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59909501/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com