日期:2014-05-17 浏览次数:20513 次
以eschop的商品表,跟订单表为例: 新建商品表 create table goods( id int auto_increment primary key, #商品id name varchar(30) not null default '',#商品名 num tinyint not null default 0 #商品数量 )engine myisam default charset utf8; 新建订单变 create table indent( oid int auto_increment primary key, #订单id gid int not null default 0, #商品id much tinyint not null default 0 #购买数量 )engine myisam default charset utf8; mysql> desc goods; +-------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+-------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | name | varchar(30) | NO | | | | | num | tinyint(4) | NO | | 0 | | +-------+-------------+------+-----+---------+----------------+ 3 rows in set mysql> desc indent; +-------+------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------+------------+------+-----+---------+----------------+ | oid | int(11) | NO | PRI | NULL | auto_increment | | gid | int(11) | NO | | 0 | | | much | tinyint(4) | NO | | 0 | | +-------+------------+------+-----+---------+----------------+ 插入演示数据: insert into goods values(1,'三星手机',12),(2,'ipad电脑',19),(3,'摩托罗拉mp3',38); mysql> select * from goods; +----+-------------+-----+ | id | name | num | +----+-------------+-----+ | 1 | 三星手机 | 12 | | 2 | ipad电脑 | 19 | | 3 | 摩托罗拉mp3 | 38 | +----+-------------+-----+ 手工给订单表添加购买记录: insert into indent(gid,much)values(3,2); mysql> select * from indent; +-----+-----+------+ | oid | gid | much | +-----+-----+------+ | 1 | 3 | 2 | +-----+-----+------+ 1 row in set 手工给商品表减少商品信息: update goods set num=num-2 where id=3; mysql> select * from goods; +----+-------------+-----+ | id | name | num | +----+-------------+-----+ | 1 | 三星手机 | 12 | | 2 | ipad电脑 | 19 | | 3 | 摩托罗拉mp3 | 36 | +----+-------------+-----+ 3 rows in set 修改mysql的结束符: mysql> delimiter $ ------------------------------------------- 创建触发器 create trigger tg1 after insert #在插入之后触发 on indent for each row #固定写法 begin update goods set num=num-1 where id=3; end $ ------------------------------------------ 模拟用户下订单流程 商品表: +----+-------------+-----+ | id | name | num | +----+-------------+-----+ | 1 | 三星手机 | 12 | | 2 | ipad电脑 | 19 | | 3 | 摩托罗拉mp3 | 36 | +----+-------------+-----+ 订单表: +-----+-----+------+ | oid | gid | much |