1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| --------------
START TRANSACTION
--------------
--------------
DROP DATABASE IF EXISTS `base`
--------------
--------------
CREATE DATABASE IF NOT EXISTS `base`
DEFAULT CHARACTER SET `latin1`
DEFAULT COLLATE `latin1_general_ci`
--------------
--------------
DROP TABLE IF EXISTS `test`
--------------
--------------
CREATE TABLE `test`
( `id` integer unsigned NOT NULL auto_increment primary key,
`tri` smallint unsigned NOT NULL,
`certifie` tinyint unsigned NOT NULL,
`numero_facture` integer unsigned NULL,
index `idx` (`tri`,`certifie`)
) ENGINE=InnoDB
DEFAULT CHARSET=`latin1` COLLATE=`latin1_general_ci`
ROW_FORMAT=COMPRESSED
--------------
--------------
DROP TRIGGER IF EXISTS `increment`
--------------
--------------
CREATE TRIGGER `increment`
BEFORE INSERT ON `test`
FOR EACH ROW
BEGIN
SET NEW.numero_facture = case when new.certifie = 1 then ifnull((select max(numero_facture)+1 from `test` where tri=NEW.tri),1) else 0 end;
END
--------------
--------------
insert into `test` (`tri`,`certifie`) values
(1,1),(1,0),(1,0),(1,1),(1,1),(1,0),(1,1),
(2,1),(2,1),(2,0),(2,1),
(3,0),(3,1),(3,0),(3,1)
--------------
--------------
select * from `test`
--------------
+----+-----+----------+----------------+
| id | tri | certifie | numero_facture |
+----+-----+----------+----------------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 0 | 0 |
| 3 | 1 | 0 | 0 |
| 4 | 1 | 1 | 2 |
| 5 | 1 | 1 | 3 |
| 6 | 1 | 0 | 0 |
| 7 | 1 | 1 | 4 |
| 8 | 2 | 1 | 1 |
| 9 | 2 | 1 | 2 |
| 10 | 2 | 0 | 0 |
| 11 | 2 | 1 | 3 |
| 12 | 3 | 0 | 0 |
| 13 | 3 | 1 | 1 |
| 14 | 3 | 0 | 0 |
| 15 | 3 | 1 | 2 |
+----+-----+----------+----------------+
--------------
COMMIT
--------------
Appuyez sur une touche pour continuer... |
Partager