你可以做到這一點與這2個查詢。第一個插入一個新部門或增加計數,如果它存在。第二次讀最後的計數。你也可以把一個存儲過程中
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>
兩個查詢生成的代碼,同時保存數據。而不是在保存記錄時從服務器獲取代碼。用計數器設置一個新列來計算部門 – rashfmnb
您的問題本質上是一系列的requirements_。 [問] – MickyD