mysql触发器语句

uvcms 2009-07-21 10:45:59
写个MySql5.1.36触发器,当在AA表中列title插入数据时
判断BB表中列title是否存在相同值
如果不存在,则在BB表中列title也插入数据
如果存在,则在BB表中列num加1
怎么写阿?
...全文
106 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
wfnychuan 2009-07-22
  • 打赏
  • 举报
回复

delimiter //
create trigger tri_update_bb after insert on aa
for each row
begin
set @n=(select count(*) from bb where bb.title=new.title);
if @n>0 then
update BB set num=num+1 where title=new.title;
else
insert into BB(title,num) values (new.title,1);
end if;
end;
delimiter ;
hitexam 2009-07-21
  • 打赏
  • 举报
回复
create trigger testref after insert on AA
for each row
begin
set @x=(select count(*) from BB where BB.title=NEW.title);
if @x>0 then
update BB set num=num+1 where title=NEW.title;
else
insert into BB (num,title) values (1,New.title);
end if;
end;
ACMAIN_CHM 2009-07-21
  • 打赏
  • 举报
回复
mysql> create table AA (id int primary key,title int);
Query OK, 0 rows affected (0.05 sec)

mysql> create table BB (title int primary key,num int);
Query OK, 0 rows affected (0.11 sec)

mysql> delimiter //
mysql>
mysql> create trigger tr_AA_bi before insert on AA
-> for each row
-> begin
-> insert into BB (title,num) values (new.title,1)
-> ON DUPLICATE KEY UPDATE num=num+1;
-> end;
-> //
Query OK, 0 rows affected (0.11 sec)

mysql> delimiter ;
mysql>

mysql> insert into AA values (2,1);
Query OK, 1 row affected (0.06 sec)

mysql> insert into AA values (1,1);
Query OK, 1 row affected (0.23 sec)

mysql> select * from aa;
+----+-------+
| id | title |
+----+-------+
| 1 | 1 |
+----+-------+
1 row in set (0.00 sec)

mysql> select * from bb;
+-------+------+
| title | num |
+-------+------+
| 1 | 1 |
+-------+------+
1 row in set (0.00 sec)

mysql> select * from aa;
+----+-------+
| id | title |
+----+-------+
| 1 | 1 |
| 2 | 1 |
+----+-------+
2 rows in set (0.00 sec)

mysql> select * from bb;
+-------+------+
| title | num |
+-------+------+
| 1 | 2 |
+-------+------+
1 row in set (0.00 sec)

mysql>

56,687

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧