-- 首先在db_exercise1下新建一个账户表
use db_exercise1;
create table if not exists tb_account(
cid int primary key auto_increment comment '账户编号',
cname varchar(255) comment '账户名称',
balance decimal(10,2) comment '账户余额'
);
-- 插入两个用户
insert into tb_account(cname,balance) values
('甲人',10000),
('乙人',0);
-- 检查表中内容
select * from tb_account;-- 执行更新数据时报错: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column. To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
-- 解决方案:SET SQL_SAFE_UPDATES = 0;-- 第一个事务:通过事务完成转账操作
begin;
update tb_account set balance=balance-3000 where cname='甲人';
update tb_account set balance=balance+3000 where cname='乙人';
commit;-- 第二个事务:转账过程中如果不一致(违反一致性,就要回滚数据)
begin;
update tb_account set balance=balance-1000 where cname='甲人';
update tb_account set balance=balance+1500 where cname='乙人';
rollback;
-- 语句
create view v_视图名 as select 语句;
注意:这个功能就是把select语句的结果用一个名字定义,下次使用这个结果可以直接通过这个名字。视图中的数据可以修改,但是前提是这个数据必须是来自原表的数据(修改了原表数据,原表也会发生改变),如果是通过聚合函数之类的函数统计得到的数据,视图是无法修改的,会报错。
explain sql语句;
注意:想要提高查询效率,尽量通过“索引键”查询。
create index idx_索引名 on 表名(字段名(元素下标)); -- 下标从1开始
举例:
create index idx_索引名1_索引名2.. on 表名(字段名1,字段名2,..); -- 下标从1开始
举例: