如何编写触发器以在MySql

时间:2015-12-07 13:05:12

标签: mysql triggers

我有两张表usersmedia

当我插入新用户时,我想创建一个触发器来自动插入新的media行,获取新插入的mediaid来更新users }。media_id

怎么办呢?感谢帮助

修改

这是媒体表定义。 media_id是自动增量的主键。

CREATE TABLE `media` (
  `media_id` int(10) UNSIGNED NOT NULL,
  `media_image` tinytext,
  `media_create_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `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
)

1 个答案:

答案 0 :(得分:1)

<强>设置

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
);

触发器定义

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)