一、选择数据库
use test;
二、查看当前环境的字符集编码
一定要保证客户端和服务端字符集编码一致,比如表中插入中文时,避免出现乱码!
如果数据库字符集编码是utf8,而插入端是gbk或者说反过来,二者就会冲突,最后造成表中的数据中文乱码
mysql> show variables like '%character%';
+--------------------------+-----------------------------------------------+
| Variable_name | Value |
+--------------------------+-----------------------------------------------+
| character_set_client | utf8 |
| character_set_connection | utf8 |
| character_set_database | utf8 |
| character_set_filesystem | binary |
| character_set_results | utf8 |
| character_set_server | utf8 |
| character_set_system | utf8 |
| character_sets_dir | E:\wamp\bin\mysql\mysql5.6.12\share\charsets\ |
+--------------------------+-----------------------------------------------+
三、创建表
(1)主表A:
create table A
(id int not null auto_increment primary key,
name varchar(10) not null
);
(2)子表B(和表A通过a_id关联)
create table B
(id int not null auto_increment primary key,
a_id int not null,
job varchar(20) not null
);
(3)A表删除记录的备份表A_del_bak
create table A_del_bak
(id int not null ,
name varchar(10) not null,
delTime datetime
);
四、插入表数据
insert into A(name) values('appleyk');
insert into A(name) values('张三');
insert into A(name) values('李四');
insert into B values(1,1,'Java');
insert into B values(2,2,'Delphi');
insert into B values(3,3,'C++');
五、使用内连接inner join连接A和B,组合查询数据
select a.id as aid,b.id as bid,a.name,b.job from A a inner join B b on a.id=b.a_id;
六、为表A创建一个触发器,基于删除操作,目的是在删除数据前
(1)备份要删除的数据到表A_del_bak,并记录删除数据的时间
(2)同时删除与表A关联的子表B中,和A相关的记录
delimiter @
drop trigger if exists A_DEL_BEFORE;
create trigger A_DEL_BEFORE before delete on A for each row
begin
insert into A_del_bak select id,name,now() from A where id = old.id;
delete from B where a_id = old.id;
end;
@
mysql默认的一条语句执行完,是';',如果执行的是一个代码块的话,需要修改分隔符,否则,代码块中遇到';'号就结束,导致你死活不能完整的创建一个存储过程或者一个触发器,因此,我们需要在一开始,指定一个分隔符为'@',最后创建完我们的代码块后,再以'@'结尾,这样的话,才能创建我们的触发器A_DEL_BEFORE
用完,记得,将delimiter再置回来
七、删除A表中,id = 1的记录
(1)删除前,看一眼记录集
select*from A;
(2)执行删除
delete from A where id=1;
(3)删除后,触发器A_DEL_BEFORE的作用效果如下
A. 表A_del_bak增加了一条记录,来自于表A的记录删除
select*from A_del_bak;
B.同时表B中,关于a_id = 1的记录被移除
select*from B where a_id = 1;
C.我们再一次用A和B内连接,组合查询数据如下
select a.id as aid,b.id as bid,a.name,b.job from A a inner join B b on a.id=b.a_id;