setup
CREATE TABLE `media` (
`media_id` int(10) UNSIGNED NOT NULL,
`media_image` tinytext,
`media_create_date` datetime NOT NULL,
`media_update_date` datetime NOT NULL
);
CREATE TABLE `tf_user` (
`user_id` int(10) UNSIGNED NOT NULL,
`user_name` varchar(50) NOT NULL,
`user_email` varchar(100) NOT NULL,
`user_gender` varchar(1) NOT NULL,
`user_media_id` int(10) UNSIGNED
);
trigger definition
CREATE TABLE `seq` (
`val` int(10) unsigned NOT NULL,
PRIMARY KEY (`val`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
insert into seq(val) values(1);
delimiter $$
create function seq() returns int
begin
update seq set val=last_insert_id(val+1);
return last_insert_id();
end $$
create trigger tr_ins_user before insert
on tf_user for each row
begin
declare media_id int(10);
select seq() into media_id;
insert into media
( media_id, media_image, media_create_date, media_update_date )
select media_id, null as media_image,
current_date as media_create_date, null as media_update_date
;
set NEW.user_media_id = media_id;
end $$
delimiter ;
IO
mysql> insert into tf_user(user_id, user_name, user_email, user_gender, user_media_id) values(3, 'test', 'test@test.com', 'M', -1);
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> select *
-> from tf_user
-> ;
+---------+-----------+---------------+-------------+---------------+
| user_id | user_name | user_email | user_gender | user_media_id |
+---------+-----------+---------------+-------------+---------------+
| 3 | test | test@test.com | M | 2 |
+---------+-----------+---------------+-------------+---------------+
1 row in set (0.00 sec)
mysql> select *
-> from media
-> ;
+----------+-------------+---------------------+---------------------+
| media_id | media_image | media_create_date | media_update_date |
+----------+-------------+---------------------+---------------------+
| 2 | NULL | 2015-12-08 00:00:00 | 0000-00-00 00:00:00 |
+----------+-------------+---------------------+---------------------+
1 row in set (0.00 sec)