我们有一个要求,我们将自动生成一个字段值。自动值的格式应该是Currentyear-Dept-001.根据部门,计数器需要递增,如果部门是英语,2016-English-001 next 2016-English-002,如果部门是数学计数器需要从2016-Maths-001开始。我正在考虑创建一个API,它可以接受部门名称并返回每个部门自动生成的值。如果是这样,我将不得不在数据库中创建一个表,如何单独为每个部门设置计数器?因为我们没有数据库中的部门,所以新部门有时会进来。现在不知道如何继续这样做。非常感谢任何帮助
答案 0 :(得分:3)
你可以用这两个查询来做到这一点。第一个插入新部门或增加计数(如果存在)。第二次读取最后一次计数。您还可以将两个查询放在存储过程中
INSERT INTO myDept (Dept) VALUES ('English')
ON DUPLICATE KEY UPDATE cnt = cnt +1;
SELECT Dept, CONCAT(YEAR(NOW()),'-',Dept,'-',cnt) as Dept_cnt
FROM myDept
WHERE Dept = 'English';
<强>样品强>
mysql> SELECT * FROM myDEpt;
Empty set (0,00 sec)
mysql> INSERT INTO myDept (Dept) VALUES ('English')
-> ON DUPLICATE KEY UPDATE cnt = cnt +1;
Query OK, 1 row affected (0,00 sec)
mysql>
mysql> SELECT Dept, CONCAT(YEAR(NOW()),'-',Dept,'-',cnt) as Dept_cnt
-> FROM myDept
-> WHERE Dept = 'English';
+---------+----------------+
| Dept | Dept_cnt |
+---------+----------------+
| English | 2016-English-1 |
+---------+----------------+
1 row in set (0,00 sec)
mysql> INSERT INTO myDept (Dept) VALUES ('English')
-> ON DUPLICATE KEY UPDATE cnt = cnt +1;
Query OK, 2 rows affected (0,00 sec)
mysql>
mysql> SELECT Dept, CONCAT(YEAR(NOW()),'-',Dept,'-',cnt) as Dept_cnt
-> FROM myDept
-> WHERE Dept = 'English';
+---------+----------------+
| Dept | Dept_cnt |
+---------+----------------+
| English | 2016-English-2 |
+---------+----------------+
1 row in set (0,00 sec)
mysql> SELECT * FROM myDEpt;
+---------+------+
| Dept | cnt |
+---------+------+
| English | 2 |
+---------+------+
1 row in set (0,00 sec)
mysql> INSERT INTO myDept (Dept) VALUES ('Math')
-> ON DUPLICATE KEY UPDATE cnt = cnt +1;
Query OK, 1 row affected (0,00 sec)
mysql>
mysql> SELECT Dept, CONCAT(YEAR(NOW()),'-',Dept,'-',cnt) as Dept_cnt
-> FROM myDept
-> WHERE Dept = 'Math';
+------+-------------+
| Dept | Dept_cnt |
+------+-------------+
| Math | 2016-Math-1 |
+------+-------------+
1 row in set (0,00 sec)
mysql> SELECT * FROM myDEpt;
+---------+------+
| Dept | cnt |
+---------+------+
| English | 2 |
| Math | 1 |
+---------+------+
2 rows in set (0,00 sec)
mysql>