数据库之mysql视图、触发器、事务、存储过程、函数等相关内容-47
# =============================创建视图
select * from emp inner join dep on emp.dep_id = dep.id;
create view emp2dep as select emp.*,dep.name as dep_name from emp inner join dep on emp.dep_id = dep.id;
mysql> update emp2dep set name="EGON" where id=1;
Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> select * from emp2dep;
+----+-----------+--------+------+--------+--------------+
| id | name | sex | age | dep_id | dep_name |
+----+-----------+--------+------+--------+--------------+
| 1 | EGON | male | 18 | 200 | 技术 |
| 2 | alex | female | 48 | 201 | 人力资源 |
| 3 | wupeiqi | male | 38 | 201 | 人力资源 |
| 4 | yuanhao | female | 28 | 202 | 销售 |
| 5 | liwenzhou | male | 18 | 200 | 技术 |
+----+-----------+--------+------+--------+--------------+
5 rows in set (0.00 sec)
mysql>
mysql>
mysql> select * from emp;
+----+------------+--------+------+--------+
| id | name | sex | age | dep_id |
+----+------------+--------+------+--------+
| 1 | EGON | male | 18 | 200 |
| 2 | alex | female | 48 | 201 |
| 3 | wupeiqi | male | 38 | 201 |
| 4 | yuanhao | female | 28 | 202 |
| 5 | liwenzhou | male | 18 | 200 |
| 6 | jingliyang | female | 18 | 204 |
| 7 | lili | female | 48 | NULL |
+----+------------+--------+------+--------+
7 rows in set (0.00 sec)
mysql>
# =============================修改视图
alter view emp2dep as 查询语句;
# =============================删除视图
drop view emp2dep;
2.触发器
使用触发器可以定制用户对表进行【增、删、改】操作时前后的行为,注意:没有查询
# 增=》insert
delimiter //
create trigger tri_before_insert_t1 before insert on t1 for each row
begin
sql语句;
end //
delimiter ;
create trigger tri_after_insert_t1 after insert on t1 for each row
begin
sql语句;
end
# 删除=》delete
create trigger tri_before_delete_t1 before delete on t1 for each row
begin
sql语句;
end
create trigger tri_after_delete_t1 after delete on t1 for each row
begin
sql语句;
end
# 修改=》update
# 例如
insert into tt1 values(1,"egon",'male');
delimiter //
create trigger tri_before_insert_tt1 before insert on tt1 for each row
begin
insert into tt2 values(NEW.name);
end //
delimiter ;
insert into tt1 values(2,"tom",'female');
# 练习
CREATE TABLE cmd (
id INT PRIMARY KEY auto_increment,
USER CHAR (32),
priv CHAR (10),
cmd CHAR (64),
sub_time datetime, #提交时间
success enum ('yes', 'no') #0代表执行失败
);
CREATE TABLE errlog (
id INT PRIMARY KEY auto_increment,
err_cmd CHAR (64),
err_time datetime
);
delimiter $$
create trigger tri_after_insert_cmd after insert on cmd for each row
begin
if NEW.success = 'no' then
insert into errlog(err_cmd,err_time) values(NEW.cmd,NEW.sub_time);
end if;
end $$
delimiter ;
insert into cmd(user,priv,cmd,sub_time,success) values
('egon','0755','ls -l /etc',NOW(),'yes'),
('egon','0755','cat /etc/passwd',NOW(),