0

How create a Auto increment field based on this example:

I have this table, with "AF" field, in that format: SN.MM.YYYY The "SN" = AI number based on last insert, MM= Atual Month, YYYY = Atual Year.

| ID |    AF       | 
____________________
|  1 | 01.10.2013  |
|  2 | 02.10.2013  |

So, when changes the month or year, the trigger must set "AF" field that way: Ex.: Month changes to November(Reset SN to 01).

|  3 | 01.11.2013  |
|  4 | 02.11.2013  |

The same thing when year changes(Reset SN to 01):

|  5 | 01.01.2014  |
|  6 | 02.01.2014  |
|  7 | 03.01.2014  |

Anyone know's how set that trigger?

Obs: There may be more than one record in one day, so, day is not important.

Sorry for the bad english

Thanks guys!

4

1 回答 1

1

从技术上讲,你可以做这样的事情

CREATE TRIGGER tg_bi_table1
BEFORE INSERT ON table1
FOR EACH ROW
  SET NEW.af = CONCAT(
    LPAD(COALESCE(
      (SELECT MAX(LEFT(af, 2)) 
         FROM table1 
        WHERE af LIKE DATE_FORMAT(CURDATE(), '__.%m.%Y')), 0) + 1, 2, '0'), 
    DATE_FORMAT(CURDATE(), '.%m.%Y'));

这是SQLFiddle演示

注意:这种方法(使用这种模式创建您自己的 ago_increment 值)有两个主要缺点:

  1. 在高并发访问下,不同的连接可能会获得相同的AF数
  2. 由于您的特定 AF 模式(SN 优先)使用索引是不可能的,因此您最终总是会得到完整扫描
于 2013-10-23T14:50:53.723 回答