MySQL "on duplicate"  

Posted in ,

No way to use "update table" in a before update trigger.
Good sample, that shows it.

If you trying to use update operations on table with trigger connected to it,
operation falls with error


ERROR 1442 (HY000): Can't update table 'table_name' in stored function/trigger because it is already used by statement which invoked this stored function/trigger.


Using stored procedures don't resolve this issue.
You will get same error (1422).

MySQL have solution for an action on duplicate triggers event.
But this work only if constraint is "UNIQUE KEY" and you want to insert
a duplicate value.


DROP TABLE IF EXISTS `test`.`test1`;
CREATE TABLE `test`.`test1` (
`id` int(10) unsigned NOT NULL,
`key` int(10) unsigned NOT NULL,
`data` varchar(45) NOT NULL default '2',
`id_inc` int(10) unsigned NOT NULL auto_increment,
PRIMARY KEY USING BTREE (`id_inc`,`id`),
UNIQUE KEY `_UNIQUE` USING BTREE (`key`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

insert into test1 (id,`key`,`data`) values (1,1,'1');
insert into test1 (id,`key`,`data`) values (2,2,'2');


insert into test1 (`id`, `key`,`data`) values (2, 3, '3') on duplicate key update `data` = '`id` no double key 2';
insert into test1 (`id`, `key`,`data`) values (3, 3, '3') on duplicate key update `data` = '`key` no double key 3';
insert into test1 (`id_inc`, `id`, `key`,`data`) values (2, 4, 4,'4') on duplicate key update `data` = '`id_inc` no double key 2';
insert into test1 (`id_inc`) values (1) on duplicate key update `data` = '`id_inc` no double key 1';
insert into test1 (`id`, `key`,`data`) values (5, 5,'5');

select * from test1;

+----+-----+-----------------------+--------+
| id | key | data | id_inc |
+----+-----+-----------------------+--------+
| 0 | 0 | 2 | 1 |
| 1 | 1 | 1 | 1 |
| 2 | 2 | 2 | 2 |
| 4 | 4 | 4 | 2 |
| 2 | 3 | `key` no double key 3 | 3 |
| 5 | 5 | 5 | 4 |
+----+-----+-----------------------+--------+
6 rows in set (0.00 sec)

0 responzez

Post a Comment

metanews


Add to Google