在mysql中创建一个基于年份、月份和我的自定义编号的ID列


Create an ID column in mysql based on year, month and then my custom number

我只想在mysql中使用15070000115000001(yymm00001)格式的ID列,也就是primary key。我在下面试过这个代码

 select ifnull(lpad(max(pid)+1,9, '0'), 
 concat(concat(DATE_FORMAT(CURDATE(), '%y'), 
 DATE_FORMAT(CURDATE(), '%m')),lpad('1',5,'0'))) pid 
 from patient_admission;

我想要:

╔═══════════╗
║ 150600001 ║
║ 150600002 ║
║ 150600003 ║
║ 150700001 ║
║ 150600002 ║
╚═══════════╝

等等

但它不会在下个月回来。Thnx。

这是我的表结构:

1.  pid {char(9), Primary Key}
2.  pname
3.  age
4.  gender
5.  marital_status
6.  profession
7.  father_name
8.  mother_name
9.  present_addr
10. permanent_addr
11. phone
12. contact_person_name
13. contact_person_phone
14. contact_person_relation
15. contact_person_addr
16. consultant_doctor
17. onduty_doctor
18. admission_fee
19. admission_date
20. bed_allotment
21. status

上面提到的代码已经过测试了。

我在CodeIgniter:上运行这个

型号部件:

public function get_patient_id(){
$sql = "select ifnull(lpad(max(pid)+1,9, '0'), concat(concat(DATE_FORMAT(CURDATE(), '%y'), DATE_FORMAT(CURDATE(), '%m')),lpad('1',5,'0'))) pid from patient_admission";
$qry = $this->db->query($sql);
$ra = $qry->result_array();
return $ra[0];
}

控制器部分:

public function entry(){
$data['patient_id'] = $this->Patient_admission_model->get_patient_id();
$this->load->view( 'patient/admission/entry', $data );

}

最后我成功地完成了,jaust必须用子查询添加where线索:

select ifnull(lpad(max(pid)+1,9, '0'), concat(DATE_FORMAT(CURDATE(), '%y%m'),lpad('1',5,'0'))) pid from patient_admission where id_generator = (select DATE_FORMAT(CURDATE(), '%y%m') id_generator)

我刚刚在patient_address表中创建了id_generator另一列和gmdate('ym',time((+3600*6(;该代码在插入期间

仅此而已。顺便说一句,感谢大家@Drew Pierce