1

I'm working on an application that will generate folios for some form filling that the user will make, internally I will handle a documentId which will be auto incremented, however I have to generate the client's folio in a diffennt format
Example:

Folio 100613A100
10 - day
06 - month
13 - year
A - if regular 
E - if special 
100 - AI number

Basically I can the first 7 digits from my PHP code however since I don't know what the AI number will be I can create this value until the insert is done,

My current approach is to do a insert without populating that field and right after the insert use LAST_INSERT_ID() to generate the Folio and update the table, but this looks kind of an overhead to me so I'm wondering if there any hidden gem in MySql that would allow to use the AI value on the insert.

Note that I can't use LAST_INSERT_ID() id before the insert as the app will have concurrent access, my implementation is working just fine and I don't have any issue with it I'm just wondering if is possible for the sake of gaining a little bit of knowldege.

4

2 に答える 2

2

BEFORE INSERTシーケンス用のトリガーと別のテーブル (気にしない場合) を使用して、挿入時に Folio 番号を生成するという目標を達成できます。

まずは順番表

CREATE TABLE table1_seq 
  (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY);

実際のテーブル

CREATE TABLE Table1
  (`id` INT NOT NULL DEFAULT 0, 
   `folio` VARCHAR(32)
   ...
  );

トリガー

DELIMITER $$
CREATE TRIGGER tg_table1_insert 
BEFORE INSERT ON Table1
FOR EACH ROW
BEGIN
  INSERT INTO table1_seq VALUES (NULL);
  SET NEW.id = LAST_INSERT_ID();
  SET NEW.folio = CONCAT(DATE_FORMAT(CURDATE(), '%d%m%y'), UPPER(NEW.folio), NEW.id);
END$$
DELIMITER ;

これで、新しいレコードを挿入できます

INSERT INTO Table1 (`folio`, ...)
VALUES ('a', ...), ('e', ...);

そして、あなたはあなたのtable1にあります

| | ID | フォリオ |...
------------------...
| | 1 | 160613A1 |...
| | 2 | 160613E2 |...

これがSQLFiddle のデモです。

別の方法は、ストアド プロシージャでINSERTandをラップすることです。UPDATE

DELIMITER $$
CREATE PROCEDURE sp_table1_insert (IN folio_type VARCHAR(1), ...)
BEGIN
  DECLARE newid INT DEFAULT 0;
  START TRANSACTION;
  INSERT INTO table1 (id, ...) VALUES (NULL, ...);
  SET newid = LAST_INSERT_ID();
  UPDATE table1 
     SET folio = CONCAT(DATE_FORMAT(CURDATE(), '%d%m%y'), UPPER(folio_type), newid)
   WHERE id = newid;
  COMMIT;
END$$
DELIMITER ;

次に、このストアド プロシージャを使用して新しいレコードを挿入します

CALL sp_table1_insert ('a',...);
CALL sp_table1_insert ('e',...);

これがそのためのSQLFiddleデモです。

于 2013-06-16T02:52:31.613 に答える
1

AFTER INSERT TRIGGERを使用できます。このマニュアルを参照してください: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

于 2013-06-16T02:05:14.020 に答える