一般的に使用されるSQLステートメント-使用して確認する

 

 


CREATE TABLE `MARS_Keyword` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(词包ID)',
  `Keyword` varchar(256) NOT NULL DEFAULT '' COMMENT '关键词(词包名)',
  `Word` text COMMENT '词包(英文逗号分隔的字符串)',
  `Bu` varchar(256) NOT NULL DEFAULT '' COMMENT '适用BU',
  `Category` text COMMENT '适用类目(一二三级类目)',
  `DpCategory` text COMMENT '点评侧溢价类目',
  `MtCategory` text COMMENT '美团侧溢价类目',
  `Status` int(11) NOT NULL DEFAULT '1' COMMENT '1-有效,0-无效',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`),
  UNIQUE KEY `UNIQUE_IX_Keyword` (`Keyword`)
) ENGINE=InnoDB AUTO_INCREMENT=86 DEFAULT CHARSET=utf8;


CREATE TABLE `RUN_Department` (
  `DepartmentId` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(部门ID)',
  `DepartmentName` VARCHAR(256) NOT NULL DEFAULT '' COMMENT '部门名称',
  `Status` TINYINT(4) NOT NULL DEFAULT '1' COMMENT '部门是否有效:1-有效,0-无效',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`DepartmentId`),
  UNIQUE KEY `UNIQUE_IX_DepartmentName` (`DepartmentName`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;


insert into RUN_Department(DepartmentName) values("商家投放组");
insert into RUN_Department(DepartmentName) values("商家财务组");
insert into RUN_Department(DepartmentName) values("商家供应链组");
insert into RUN_Department(DepartmentName) values("商家引擎组");

select * from RUN_Department;
drop table RUN_Employee;

CREATE TABLE `RUN_Employee` (
  `EmployeeId` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(员工ID)',
  `EmployeeName` VARCHAR(256) NOT NULL DEFAULT '' COMMENT '员工姓名',
  `EmployeeSex` TINYINT(4) NOT NULL COMMENT '员工性别(1-男,2-女,3-未知)',
  `EmployeeAge` TINYINT(4) NOT NULL COMMENT '员工年龄',
  `DepartmentId` INT(11) NOT NULL COMMENT '员工所属部门',
  `EmployeeScore` INT(11) NOT NULL DEFAULT 0 COMMENT '员工得分(0-100)',
  `Status` TINYINT(4) NOT NULL DEFAULT '1' COMMENT '员工是否在职:1-在职,0-离职',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`EmployeeId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('小陈',1,20,1,99);
insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('小红',1,21,2,93);
insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('小橙',2,19,3,95);
insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('小黄',1,22,4,97);
insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('小绿',1,23,4,99);
insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('小青',2,29,1,98);

select * from RUN_Employee;

alter table RUN_Employee add EmployeeScore TINYINT(4) NOT NULL DEFAULT 0 COMMENT '员工得分(0-100)';
show create table RUN_Employee;
select * from runoob_tbl;

select * from `RUN_Employee`;
select * from `RUN_Department`;
select * from `RUN_Employee` e left join `RUN_Department` d on e.`DepartmentId`=d.`DepartmentId`;
select EmployeeName,count(*) from `RUN_Employee` where `Status`=1 GROUP BY EmployeeName;
select re.DepartmentId,rd.`DepartmentName`,count(*) from `RUN_Employee` re join `RUN_Department` rd on rd.`DepartmentId`=re.DepartmentId where re.`Status`=1 GROUP BY re.DepartmentId;
insert into `RUN_Department`(DepartmentName) values('商家测试组');
insert into `RUN_Department`(DepartmentName) values('商家产品组');
insert into `RUN_Employee` (EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values('张飞',1,99,20,98);
update `RUN_Employee` set DepartmentId=8 where EmployeeId=8;
#Join查询:A表是左表,B表是右表
#(1)A和B共有的
select * from `RUN_Employee` e join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`;
#(2)A和B共有的+A独有的
select * from `RUN_Employee` e left join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`;
#(3)A和B共有的+B独有的
select * from `RUN_Employee` e right join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`;
#(4)A独有的
select * from `RUN_Employee` e left join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId` where d.`DepartmentId` is null;
#(5)B独有的
select * from `RUN_Employee` e right join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId` where e.`EmployeeId` is null;
#(6)AB并集:AB交集+A独有+B独有
select * from `RUN_Employee` e left join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`
union select * from `RUN_Employee` e right join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`;
#(7)AB独有的并集:相当于A、B并集去掉AB的交集
explain
select * from `RUN_Employee` e left join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId` where d.`DepartmentId` is null
union select * from `RUN_Employee` e right join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId` where e.`EmployeeId` is null;

select `EmployeeScore`+ifnull(EmployeeAge,100) from `RUN_Employee`;

select * from RUN_Employee where employeeScore REGEXP '^9+';
select * from RUN_Employee where employeeScore REGEXP '^9*';
select * from RUN_Employee where employeeScore REGEXP '^[8+|9+]';
select * from RUN_Employee where employeeScore REGEXP '9$';
select * from RUN_Employee where employeeScore REGEXP '^9';
select * from RUN_Employee where employeeScore REGEXP '^[78]|1$';

#声名一个无参存储过程
delimiter $
create procedure proTest()
begin 
select * from MARS_Keyword mk where mk.id between 1 and 10;
end $
#调用一个存储过程
call proTest();
#查看一个存储过程
show procedure status;
show create procedure proTest;
#删除一个存储过程
drop procedure proTest;

#声名一个有参存储过程
delimiter $
create procedure proTestIN(in ID int)
begin 
select * from MARS_Keyword mk where mk.id=ID;
end $
#调用一个有参存储过程
call proTestIN(1);

select * from `RUN_OOB`;
select * from `RUN_Department`;
select * from `RUN_Employee`;
show index from RUN_Employee;
alter table RUN_Employee add unique index IX_Unique_Name_Sex(EmployeeName,EmployeeSex);
alter table RUN_Employee drop index IX_Unique_Name_Sex;

#开启事务、执行事务、回滚事务
begin;    #开启一个事务
insert into `RUN_Department`(`DepartmentName`) values("商家测试二组2"); #操作语句
insert into `RUN_Department`(`DepartmentName`) values("商家产品二组2"); #操作语句
commit;   #提交一个事务去执行(提交的事务具有ACID特性:原子性/一致性/隔离性/持久性)
rollback; #回滚一个事务(当一个事务没有被commit之前可以被回滚)

show table status;
select * from `RUN_OOB`;
select * from `RUN_OOB_Copy`;
select * from `RUN_OOB_Copy2`;
#复制表的方式1
#1.显示建表语句
show create table `RUN_OOB`;
#2.创建表结构,注意AUTO_INCREMENT字段
CREATE TABLE `RUN_OOB_Copy` (
  `runoob_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `runoob_title` varchar(100) NOT NULL,
  `runoob_author` varchar(40) NOT NULL,
  `submission_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '时间',
  PRIMARY KEY (`runoob_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
#3.复制老表数据到新表中去
insert into RUN_OOB_Copy(runoob_id,runoob_title,runoob_author,submission_date) select runoob_id,runoob_title,runoob_author,submission_date from RUN_OOB;
#复制表的方式2
create table RUN_OOB_Copy2 like RUN_OOB_Copy;
insert into RUN_OOB_Copy2 select * from RUN_OOB_Copy;
drop table RUN_OOB_Copy;
drop table RUN_OOB_Copy2;
#获取最后的插入表中的自增列的值
select last_insert_id();
#服务器版本信息
select version();
#当前数据库名 (或者返回空)
select database();
#当前用户名
select user();
#服务器状态
show status;
#服务器配置变量
show VARIABLES;

select employeeName,employeeSex from RUN_Employee;
select distinct employeeName,employeeSex from RUN_Employee;
select employeeName from RUN_Employee group by employeeName;

select database();
select * from RUN_OOB into outfile '/Users/cmm/test4MingLing/RUN_OOB.txt';
mysqldump -u root -p RUNOOB RUN_OOB > dump.txt;

show global status like 'Innodb_page_size';
16384B字节,16KB字节;

#查看MySQL支持的存储引擎
show engines;
#查看MySQL当前的默认存储引擎
show variables like '%storage_engine%';
#如果表tb_dept存在的话请删除它
DROP TABLE IF EXISTS `tb_dept`;

CREATE TABLE `RUN_OOB` (
  `runoob_id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `runoob_title` varchar(100) NOT NULL,
  `runoob_author` varchar(40) NOT NULL,
  `submission_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '时间',
  PRIMARY KEY (`runoob_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8

select * from RUN_OOB;
show create table RUN_OOB;
desc RUN_OOB;
alter table RUN_OOB add index IX_

select 1+1;
select 1=1;
select 1=10;
select null is null;
select null;
select ''='';

select version();
show index from `RUN_Department`;
explain
select * from `RUN_Department`;
explain
select * from `RUN_Department` r where r.`DepartmentId`=1;
explain
select * from `RUN_Employee` e,`RUN_Department` d where d.`DepartmentId`=e.`DepartmentId` and e.`EmployeeName`='小红';

explain select * from `RUN_Employee` e order by e.`EmployeeName`;
show index from `RUN_Employee`;
alter table `RUN_Employee`drop index IX_Name;
alter table `RUN_Employee` add index IX_Name(`EmployeeName`);
alter table `RUN_Employee` add index IX_DepartmentId(`DepartmentId`);
alter table `RUN_Employee` drop index IX_DepartmentId;

select * from `RUN_Employee`;
select * from `RUN_Department`;
show index from `RUN_Employee`;

explain
select e.* from RUN_Employee e where e.`DepartmentId` in (select d.`DepartmentId` from RUN_Department d where d.`Status`=1);
explain
select * from `RUN_Employee` e where e.`DepartmentId`=1;

explain
select * from `RUN_Employee` e where e.`EmployeeId` between 2 and 6;
explain
select * from `RUN_Employee` e where e.`DepartmentId` between 2 and 6;

#默认情况下,MySQL数据库没有开启慢查询日志,需要我们手动来设置这个参数。如果不是调优需要,一般不建议开启该参数,因为开启慢查询日志或多或少会带来一定的性能影响。
#10s
show variables like '%long_query_time%';
#注:假如sql语句的运行时间正好等于long_query_time时,sql并不会被记录下来,因此判断慢查询是sql的执行时间大于long_query_time,而不是大于等于。
show variables like 'slow_query_log';
#使用该命令开启慢查询只对当前数据库生效,MySQL重启失效,如果要配置长期有效,请在my.cnf中进行配置。
set global slow_query_log=0;
set global slow_query_log=1;
set global long_query_time=10;

#存储过程示例:https://www.cnblogs.com/developer_chan/p/9229845.html
show variables like '%log_bin_trust_function_creators%';
#可通过下述形式开启该功能,也可通过在my.cnf中永久配置的方式开启该功能,在[mysqld]下配置log_bin_trust_function_creators=1。
set global log_bin_trust_function_creators=1;
show function status;
show procedure status;

#Show Profile是mysql提供的可以用来分析当前会话中sql语句执行的资源消耗情况的工具,可用于sql调优的测量。默认情况下处于关闭状态,并保存最近15次的运行结果。
#show profile默认是关闭的,并且开启后只存活于当前会话,也就说每次使用前都需要开启。
show variables like 'profiling';
set profiling=on;
select sleep(3);
#Duration字段显示的是这条SQL执行的持续时间,SQL耗时,单位是s
show profiles;
show profile cpu,block io for query 0;
show profile ALL for query 0;

-- 表锁
#1.创建mylock表,并插入5条数据。注意数据引擎使用的是MyISAM。
drop table if exists mylock;
CREATE TABLE RUN_Mylock (
    Id INT(11) PRIMARY KEY auto_increment,
    Name VARCHAR (20) NOT NULL
) ENGINE MyISAM DEFAULT charset = utf8;
insert into RUN_Mylock (name) values ('a');
insert into RUN_Mylock (name) values ('b');
insert into RUN_Mylock (name) values ('c');
insert into RUN_Mylock (name) values ('d');
insert into RUN_Mylock (name) values ('e');
#2.手动增加表锁命令。
select * from `RUN_Mylock`;
lock table tablename1 read(write),tablename2 read(write);
lock table `RUN_Mylock` read;
#3查看表是否被加锁。如果In_use不为0,则表示表被加锁。
show open tables;
#4.释放表锁命令
unlock tables;
#A、表锁(read)举例:
lock table RUN_Mylock read;
show open tables;
show open tables where in_use>0;
select * from `RUN_Mylock`;
update `RUN_Mylock` set name='a1' where id=1;
unlock tables;
#B、表锁(write)举例:
lock table RUN_Mylock write;
show open tables where in_use>0;
select * from `RUN_Mylock`;
update `RUN_Mylock` set name='a3' where id=1;
unlock tables;
show open tables where in_use=0;
show open tables where in_use>0;
show status like 'table%';
#主要注意两个变量的值:
#①Table_locks_immediate:产生表级锁定的次数,表示可立即获取锁的查询次数,每立即获取锁一次该值加1。
#②Table_locks_waited:出现表级锁定争用而发生等待的次数(不能立即获取锁的次数,每等待一次锁该值加1),此值高则说明存在较严重的表级锁争用情况。

#注意数据库引擎为MyISAM:
#①对MyISAM表加读锁,不会阻塞其他进程对同一表(mylock)的读操作;但是会阻塞对同一表的写请求,只有当这个读锁被释放后,才会执行其他进程的写请求。
#②在加读锁并且未释放这个读锁时,该进程不能对同一表(mylock)进行写操作,并且也不能对其他表进行操作。
#③对MyISAM表加写锁,会阻塞其他进程对同一表(mylock)的读和写操作,只有当这个写锁释放后,才会执行其他进程的读和写请求。
#④在加写锁并且未释放这个写锁时,该进程不能对其他表进行读和写操作。
#简而言之:读锁会阻塞写,但是不会阻塞读,而写锁会把读和写都阻塞。
#此外,MyISAM的读写锁调度是写优先,这也是MyISAM不适合做写为主的表的引擎,因为写锁后,其他线程不能做任何操作,大量的更新会使查询很难得到锁,从而造成长时间阻塞。

-- 行锁
drop table if exists RUN_Mylock_Innodb;
CREATE TABLE RUN_Mylock_Innodb (
    Id INT(11) PRIMARY KEY auto_increment,
    Name VARCHAR (20) NOT NULL
) ENGINE InnoDB DEFAULT charset = utf8;
insert into RUN_Mylock_Innodb values (1,'a');
insert into RUN_Mylock_Innodb values (2,'b');
insert into RUN_Mylock_Innodb values (3,'c');
insert into RUN_Mylock_Innodb values (4,'d');
insert into RUN_Mylock_Innodb values (5,'e');
select * from `RUN_Mylock_Innodb`;
select * from `RUN_Mylock`;
show index from `RUN_Mylock_Innodb`;
alter table `RUN_Mylock_Innodb` add index idx_lock_id(Id);
alter table `RUN_Mylock_Innodb` add index idx_lock_name(Name);
alter table `RUN_Mylock_Innodb` drop index idx_lock_a; 

select * from `RUN_Mylock_Innodb`;
#查看数据库是否自动提交SQL语句到MySQL服务器
show variables like 'autocommit';
set autocommit=0;
#在A会话中更新表中数据,但是没有提交该SQL语句到MySQL服务器,此时在B会话中读取查询该数据,将会查询到旧值。
update `RUN_Mylock_Innodb` set name='a1' where id=1;
#提交SQL语句后,再在B会话中读取查询该数据,将会查询到新值。
commit;

update `RUN_Mylock_Innodb` set name='a11' where id=1;
commit;


#使用脚本进行大数据量的批量插入,对特定情况下测试数据集的建立非常有用。

#1.部门表(小表)
select * from `RUN_Department`;
#2.员工表(大表)。查询SQL的原则是小表驱动大表!!!
select * from `RUN_Employee`;
#3.由于在创建函数时,可能会报:This function has none of DETERMINISTIC.....因此我们需开启函数创建的信任功能。
show status;
show variables like '%log_bin_trust_function_creators%';
set global log_bin_trust_function_creators=1;

#1.创建函数,保证每条数据都不同
#(1)创建随机生成字符串的函数。
delimiter $$
drop function if exists rand_string;
create function rand_string(n int) returns varchar(255)
begin
declare chars_str varchar(52) default 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
declare return_str varchar(255) default '';
declare i int default 0;
while i<n do
set return_str=concat(return_str,substring(chars_str,floor(1+rand()*52),1));
set i=i+1;
end while;
return return_str;
end $$

show function status like '%rand_string%';

SELECT CEILING(RAND()*900+100);

       DELIMITER $$
        DROP FUNCTION IF EXISTS `currval`$$
        CREATE DEFINER=CURRENT_USER FUNCTION `currval`(seq_name VARCHAR(50)) RETURNS INT(11)
        BEGIN
              DECLARE VALUE INTEGER;
              SET VALUE=0;
              SELECT current_value INTO VALUE
              FROM sequence 
              WHERE NAME=LCASE(seq_name);
              RETURN VALUE;
        END$$

#(2)创建随机生成编号的函数。
delimiter $$
drop function if exists `rand_num()`$$
create definer=current_user function `rand_num()`(seq_name varchar(50)) returns int(11)
begin
  declare i int;
  set i=0;
  select ceiling(rand()*90+10) into i from sequence where name=lcase(seq_name);
  return i;
end $$

select rand_num('qq');
select currval('aa');

show function status like 'rand_num()';
drop function rand_num();
select ceiling(rand()*90+10);

#2.创建存储过程用于批量插入数据
#(1)创建往RUN_Department表中插入数据的存储过程。
delimiter $$
drop procedure if exists insert_dept;
create procedure insert_dept(in start int(10),in max_num int(10))
begin
declare i int default 0;
set autocommit=0;
repeat
set i=i+1;
insert into `RUN_Department` (DepartmentName) values(rand_string(10));
until i=max_num
end repeat;
commit;
end $$
#(2)创建往RUN_Employee表中插入数据的存储过程。
delimiter $$
drop procedure if exists insert_emp;
create procedure insert_emp(in start int(10),in max_num int(10))
begin
declare i int default 0;
set autocommit=0;
repeat
set i=i+1;
insert into `RUN_Employee` (EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values(rand_string(6),1,rand_num(),rand_num(),rand_num());
until i=max_num
end repeat;
commit;
end $$


#3.具体执行过程批量插入数据
#(1)首先执行随机生成字符串的函数;然后执行随机生成编号的函数。
show function status;
#(2)查看函数是否创建成功。
show procedure status;

#4.执行存储过程,插入数据。
#a.首先执行insert_dept存储过程。
#b.然后执行insert_emp存储过程。

#5.删除函数与存储过程
#a.删除函数
#b.删除存储过程


#-- 生成 0~1 之间的随机小数
# 0 < RAND() <1
#-- 乘以 9000,变成 0~9000 之间随机小数
# 0 < RAND*9000 < 9000
#-- 加上 1000,变成 0~10000 之间的随机小数
# 0 < RAND*9000+1000 < 10000
#-- 使用 CEILING 函数向上取整,去掉后面的小数,得到一个整数
#-- 或使用 FLOOR 函数向下取整,都可以
# CEILING(RAND()*9000+1000)
#-- 或
# FLOOR(RAND()*9000+1000)
select CEILING(rand()*900+100);
select FLOOR(rand()*900+100);


#查看MySQL服务器是否打开查询缓存。参考博客:https://segmentfault.com/a/1190000003039232
show variables like '%query_cache%';
#设置MySQL服务器打开查询缓存
set query_cache_type=1;
#一般情况下,不建议开启查询缓存,因为对于一个表的更新操作,这个表上所有的查询缓存都会被清空(查询缓存的size有限制)。
#因此,除了很少更新的配置表外可以使用查询缓存来提高查询速度之外,其他的一般都不建议使用查询缓存。

show index from RUN_Department;
alter table RUN_Department add unique index UNIQUE_IX_DepartmentName(DepartmentName);
alter table RUN_Department drop index UNIQUE_IX_DepartmentName;

show function status;
show procedure status;
drop function rand_num;
drop procedure proceTest;
select * from `RUN_Department`;
select * from `RUN_Employee`;

delimiter $$
create procedure proceTest()
begin
  declare i int;
  set i=1;
  while(i<=2) do 
    insert into RUN_Department(DepartmentName) values('name');
   set i=i+1;
  end while;
end $$

call proceTest();

show variables like '%buffer%';

CREATE TABLE `RUN_Test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `a` int(11) DEFAULT NULL,
  `b` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_a` (`a`),
  KEY `IDX_b` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

DELIMITER $$
CREATE PROCEDURE proceInsert()
BEGIN
  declare i int;
  set i = 1;
  while(i<=100000) do
    insert into RUN_Test value(i,3,i);
    set i=i+1;
  end while;
END $$
call proceInsert();

select * from RUN_Test;

explain
select * from RUN_Test where a=3 and b=4;
select * from RUN_Test where b between 100 and 110;
select * from RUN_Test where b between 110 and 100;

explain
select * from RUN_Test where (a between 1 and 1000) and (b between 9000 and 10000) order by b limit 1;
explain
select * from RUN_Test where (a between 1 and 1000) and (b between 9000 and 10000);


show databases like '%RUN%';
select 1,'b';
select 1+2,3*10,10/3;
#mod函数,对两个参数取模运算。
#isnull函数,判断参数是否为空,若为空返回1,否则返回0。
#ifnull函数,2个参数,判断第一个参数是否为空,如果为空返回第二个参数的值,否则返回第一个参数的值。
select mod(10,4),isnull(null),ifnull(null,'第一个参数为空返回这个值'),ifnull(1,'第一个参数为空返回这个值,否知返回第一个参数');
select 'a' 'b';
select 'a' b;
select 'a' "b";
select 'a' as "b";
select @@sql_mode;
#ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION

select monthname(now());
select md5(1);
select user();
select database();
select version();

show variables like '%join_buffer%';
show variables like '%autocommit%';
set autocommit=0;
set autocommit=1;
show variables like 'transaction_isolation';


select * from `RUN_Department`;
select * from `RUN_Employee`;

select * from `RUN_Employee` e 
join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`;

select e.*,d.`DepartmentName` from `RUN_Employee` e 
join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`
where e.`EmployeeScore`>=90;

#1.创建一个视图
create view myview as
select e.*,d.`DepartmentName` from `RUN_Employee` e 
join `RUN_Department` d on d.`DepartmentId`=e.`DepartmentId`;
#2.使用一个视图
select * from myview;
select * from myview m where m.`EmployeeScore`>=90;
select * from myview m where m.`EmployeeSex`=2;
#3.删除一个视图
drop view myview;
#4.查看一个视图的结构
desc myview;
show create view myview;


show variables;
show global variables;
show session variables;
show global variables like '%tx%';
show session variables like '%char%';
select @@global.autocommit;
drop procedure proceTest;

select @id=3,@age=56,@name='张学友';
select @id:=3,@age:=56,@name:='张学友';
select @id;

CREATE TABLE RUN_Student(
  `Id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键Id(学号Id)',
  `Name` VARCHAR(256) NOT NULL COMMENT '学生姓名',
  `ClassId` INT(11) NOT NULL COMMENT '班级Id',
  `ClassName` VARCHAR(256) NOT NULL COMMENT '班级名称',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='学生信息表';

CREATE TABLE RUN_Class(
  `Id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键Id(班级Id)',
  `ClassName` VARCHAR(256) NOT NULL COMMENT '班级名称',
  `OtherName` VARCHAR(256) NOT NULL COMMENT '班级别名',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='班级信息表';

select * from `RUN_Student`;
select * from `RUN_Class`;
show create table RUN_Student;
desc `RUN_Student`;

insert into RUN_Student(Name,ClassId,ClassName) values ('小红',1,'');
insert into RUN_Student(Name,ClassId,ClassName) values ('小橙',2,''),('小黄',3,''),('小绿',4,''),('小青',5,''),('小蓝',6,'');
insert into RUN_Class(`ClassName`,`OtherName`) values('Java班级','Java'),('MySql班级','MySql'),('Git班级','Git'),('Spring班级','Spring'),('Maven班级','Maven'),('SpringMVC班级','SpringMVC');

select * from `RUN_Student` s join `RUN_Class` c on c.`Id`=s.`ClassId`;
select * from `RUN_Student` s left join `RUN_Class` c on c.`Id`=s.`ClassId`;
select * from `RUN_Student` s right join `RUN_Class` c on c.`Id`=s.`ClassId`;

update `RUN_Student` s join `RUN_Class` c on c.`Id`=s.`ClassId` set s.`ClassName`=c.`ClassName`;
update `RUN_Student` s left join `RUN_Class` c on c.`Id`=s.`ClassId` set s.`ClassName`='',c.`ClassName`='';


/** 登陆步骤:
  source ~/.bash_profile
  mysql -u root -p
  密:admin0001112
  host:127.0.0.1
  port:3306
  password:admin0001112
  DataBase:RUNOOB
  username:root
**/

drop table RUN_Class;
drop table RUN_Student;

CREATE TABLE `RUN_Class` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(班级)',
  `ClassName` varchar(256) NOT NULL COMMENT '班级名称',
  `Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '有效=1,无效=-1',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='班级信息表';

CREATE TABLE `RUN_Student` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(学号)',
  `Name` varchar(256) NOT NULL DEFAULT '' COMMENT '姓名',
  `ClassId` int(11) NOT NULL COMMENT '班级',
  `Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '有效=1,无效=-1',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='学生信息表';

insert into RUN_Student(Name,ClassId) values ('小橙',2),('小黄',3),('小绿',4),('小青',5),('小蓝',6);
insert into RUN_Class(`ClassName`) values('Java班级'),('MySql班级'),('Git班级'),('Spring班级'),('Maven班级'),('SpringMVC班级');


desc RUN_Class;
alter table RUN_Class modify column `Status` TINYINT(4) NOT NULL DEFAULT "1" COMMENT '有效=1,无效=-1';
desc RUN_Student;
alter table RUN_Student modify column `Status` TINYINT(4) NOT NULL DEFAULT "1" COMMENT '有效=1,无效=-1';

select * from RUN_Class;
insert into RUN_Class (ClassName) values ("Redis高级");
update RUN_Class set status = -1 where id =5;

select * from RUN_Student;
insert into RUN_Student (Name,ClassId) values ("小明",1);

select * from RUN_Class;
select * from RUN_Student;
select * from RUN_Class c join RUN_Student s on c.id = s.classId
where c.status=1 and s.status=1;



/*创建数据库javacode2018*/
show databases;
USE `RUNOOB`;
DROP DATABASE IF EXISTS `javacode2018`;
CREATE DATABASE `javacode2018`;
USE `javacode2018`;

/*创建表结构*/
DROP TABLE IF EXISTS `RUN_User`;
CREATE TABLE RUN_User (
  `Id` BIGINT AUTO_INCREMENT COMMENT '主键,用户Id',
  `Name` VARCHAR(32) NOT NULL DEFAULT '' COMMENT '姓名',
  `Age` SMALLINT NOT NULL DEFAULT 1 COMMENT '年龄',
  `Salary` DECIMAL(12,2) NOT NULL DEFAULT 0 COMMENT '薪水',
  `Sex` TINYINT NOT NULL DEFAULT 0 COMMENT '性别:0=未知,1=男,2=女',
  `Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '1=有效,-1=无效',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB CHARSET=utf8mb4 COMMENT='用户表';

SELECT * FROM RUN_User;
desc RUN_User;

insert into RUN_User(Name,Age,Salary,Sex) values ('小橙',20,2000.00,1),('小韩',22,3000.00,1),('小青',20,4000.00,2),('小橙姐姐',23,5000.00,2);

show databases;
use RUNOOB;
show tables;
desc RUN_Employee;
show index from RUN_Employee;
select * from `RUN_Student`;
select * from RUN_Department;
select * from RUN_Employee;
insert into RUN_Employee(EmployeeName,EmployeeSex,EmployeeAge,DepartmentId,EmployeeScore) values("诸葛亮",1,83,3,100);

select * from RUN_Employee;
select * from RUN_Employee group by `EmployeeId`;

select departmentId,count(employeeId) as '部门人数' from RUN_Employee group by departmentId;
select departmentId as "部门ID",employeeSex as "性别",count(employeeId) as '部门人数' from RUN_Employee group by departmentId,employeeSex order by departmentId;

select departmentId as "部门ID", employeeSex as "性别", count(employeeId) as '部门人数' 
from RUN_Employee where employeeScore>=90 group by departmentId, employeeSex having count(employeeId)>=1 order by departmentId;


select departmentId as "部门ID", count(employeeId) as '部门人数' 
from RUN_Employee where employeeScore>=90 group by departmentId having count(employeeId)>=1 order by departmentId;


select departmentId as "部门ID", count(employeeId) as '部门人数' 
from RUN_Employee where employeeScore>=90 group by departmentId order by departmentId;



select * from RUN_User;

-- 查看查询缓存是否开启
show variables like "%query_cache%";
select version();
show status like '%Qcache%';
reset query cache;


CREATE TABLE `Test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `a`  int(11) DEFAULT NULL,
  `b`  int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_a` (`a`),
  KEY `IDX_b` (`b`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

DELIMITER // 
CREATE PROCEDURE proc1()
BEGIN
  declare i int;
  set i = 1;
  while(i<=100000) do
    insert into Test value(i,3,i);
    set i=i+1;
  end while;
END //
DELIMITER ;

call proc1();

explain
select * from Test where a = 3 and b = 4;


select version();


show databases;
use RUNOOB;
show tables;
show create table RUN_User;
select * from RUN_User;
select count(*) from RUN_User;

show create table RUN_Class;
desc RUN_Class;

CREATE TABLE `RUN_Class` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(班级)',
  `ClassName` varchar(256) NOT NULL COMMENT '班级名称',
  `Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '有效=1,无效=-1',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='班级信息表'

select * from RUN_Class;
select * from RUN_Student;
insert into RUN_Class(ClassName) values("SSM整合");

select * from RUN_Student t join RUN_Class c on t.`ClassId`=c.`Id`;
select * from RUN_Student t left join RUN_Class c on t.`ClassId`=c.`Id`;
select * from RUN_Student t right join RUN_Class c on t.`ClassId`=c.`Id`;

explain
select * from RUN_Student t left join RUN_Class c on t.`ClassId`=c.`Id` and t.`Name` like "%蓝%";

explain
select * from RUN_Student t left join RUN_Class c on t.`ClassId`=c.`Id` where t.`Name` like "%蓝%";


select CURRENT_DATE;
select CURRENT_DATE();
select now();
select localTime;
select sysDate();
select year(now());
select month(now());
select week(now());

select system_user();
select user();
select version();

-- count(字段):会忽略所有的null值
select * from RUN_Class;
select count(*) from RUN_Class;
select count(1) from RUN_Class;
select count(*) from RUN_Class;
select count(id) from RUN_Class;
select md5(className) from RUN_Class where id=1;
select md5(concat(id,classname)) from RUN_Class where id=1;


-- 设置不自动提交事务
-- 设置自动提交事务(数据库都是自动提交事务)
-- 开启一个事务
-- 提交一个事务
-- 回滚一个事务

create user cmm identified by '123456';
show grants for cmm;

/*
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://localhost:3306/RUNOOB?useUnicode=true&characterEncoding=utf8&useSSL=true
username:root
password:admin1112220
*/

select version();


select * from RUN_Student;


show variables like '%isolation%';
help isolation;
level: {
     REPEATABLE READ
   | READ COMMITTED
   | READ UNCOMMITTED
   | SERIALIZABLE
}

select @@transaction_isolation, @@global.transaction_isolation;
set session transaction isolation level read uncommitted;
set session transaction isolation level read committed;
set session transaction isolation level repeatable read;
set session transaction isolation level serializable;

select @@transaction_isolation, @@global.transaction_isolation;
set global transaction isolation level read uncommitted;
set global transaction isolation level read committed;
set global transaction isolation level repeatable read;
set global transaction isolation level serializable;


select * from RUN_Class;
select * from RUN_Student;

show variables like "%autocommit%";
set autocommit=0;
set autocommit=1;
update RUN_Class set status=0 where id=8;
update RUN_Student set status=0 where id=12;

select * from RUN_Class;
select _rowid,creattime from RUN_Class;

select @@autocommit;

show open tables;
lock table RUN_Class read;
lock table RUN_Class write;
unlock tables;
show status like "%table_locks%"; 
show index from RUN_Class;
show index from RUN_Class \G;
show status like "innodb_row_lock";



show engines;
show variables like "%storage_engine%";
-- 查看MySQL默认支持的存储引擎;
show variables like "%storages_engine%";
show variables like "storages_engine";
show engine;
select * from ASM_GreyConfig where greyKey like "%launchArea.show%";
select * from RUN_Class where id>=8;
commit;
begin;
select * from RUN_Class;
select @@transaction_isolation;
set session transaction isolation level repeatable read;
insert into RUN_Class(className) values("MySQL索引课程");
set session transaction isolation level repeatable;
insert into RUN_Class(className) values("MySQL事务课程");
set session transaction isolation level read committed;
select * from RUN_Class where id=8;
update RUN_Class set className="SSM" where id=8;
update RUN_Class set className="SSM整合" where id=8;
update RUN_Class set className="SSM整合整合整合整合" where id=8;
set session transaction isolation level read uncommitted;
select @@transaction_ioslation;
rollback;
select @@transaction_isolation, @@global.transaction_isolation;
set autocommit=off;
show variables like "%autocommit%";
set autocommit=on;
show variables like "autocommit";


select DB_TRX_ID from RUN_Class;
select transaction_id from RUN_Class;
select transaction_id,roll_pointer from RUN_Class;
select _rowid,transaction_id,roll_pointer from RUN_Class;
select _rowid,transaction_id from RUN_Class;
select _rowid,transactionid from RUN_Class;
select 16384/1024;
show status like "%innodb_page_size%";
show variables like "%innodb_page_size%";
show status like "%table_locks%";
show variables like "%table_locks%";
show variables like "innodb_row_lock";
show innodb_pagesize;
unlock tables;
show status like "innodb_row_lock";
lock table RUN_Class read;
show index from RUN_Class \G;
show index from RUN_Class\G;
show index from RUN_Class;
show open tables;
unlock table RUN_Class;
unlock tables RUN_Class;
lock table RUN_Class write



-- 查看MySQL支持的存储引擎
show engines;
-- 查看MySQL默认支持的存储引擎
show variables like "%storage_engine%"



explain
select _rowId from RUN_Class;
select * from RUN_Class;   -- 1,2,3,4,5,11
select * from RUN_Student; -- 1,2,3,4,10
insert into RUN_Class (className) values("Mysql数据库");
delete from RUN_Class where id in (6,7,8,9,10);
delete from RUN_Student where id in (6,7,8,9,10,11,12,13,17);

-- 内连接=左表和右表的共有部分
select * from RUN_Class c join RUN_Student s on c.Id=s.ClassId;

-- 左外连接=左表和右表的共有部分+左表独有部分
select * from RUN_Class c left join RUN_Student s on c.Id=s.ClassId;

-- 右外连接=左表和右表的共有部分+右表独有部分
select * from RUN_Class c right join RUN_Student s on c.Id=s.ClassId;

-- 左连接=左表独有部分=左外连接-左表和右表的共有部分
select * from RUN_Class c left join RUN_Student s on c.Id=s.ClassId where s.ClassId is null;

-- 右连接=右表独有部分=右外连接-左表和右表的共有部分
explain
select * from RUN_Class c right join RUN_Student s on c.Id=s.ClassId where c.Id is null;

-- 全连接=左表所有的数据+右表所有的数据,并且使用union去重后合并
select * from RUN_Class c left join RUN_Student s on c.Id=s.ClassId
union
select * from RUN_Class c right join RUN_Student s on c.Id=s.ClassId;

-- 全外连接=左表独有的数据+独表所有的数据,并且使用union去重后合并
explain
select * from RUN_Class c left join RUN_Student s on c.Id=s.ClassId where s.ClassId is null
union
select * from RUN_Class c right join RUN_Student s on c.Id=s.ClassId where c.Id is null;


show create table RUN_Test;
select * from RUN_Test;
CREATE TABLE `RUN_Test` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `a` int(11) DEFAULT NULL,
  `b` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `IDX_a` (`a`),
  KEY `IDX_b` (`b`)
) ENGINE=InnoDB AUTO_INCREMENT=100001 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


select version();

explain 
select * from RUN_Test where b!=2;


-- 解决like "%字符串%"时索引失效的问题:方法1:like百分写右边。方法2:使用覆盖索引。
select * from RUN_Employee;
show index from RUN_Employee;
create index IX_Name_DepartmentId on RUN_Employee(EmployeeName,DepartmentId);
drop index IX_Name on RUN_Employee;
explain
select departmentId,employeeName from RUN_Employee where employeeName like "刘%";
explain
select employeeName,departmentId,employeeSex from RUN_Employee where employeeName like "刘%";

explain select * from RUN_Employee where employeeName="300";
explain select * from RUN_Employee where employeeName=300;
explain select * from RUN_Employee where employeeName="300" or employeeName="小青";
explain select * from RUN_Employee where employeeName="300" or employeeName="小青" or departmentId=1;

show index from RUN_Student
select * from RUN_Student;
select * from RUN_Class;
select * from RUN_Student where classId in ( select id from RUN_Class );
select * from RUN_Student s where exists ( select * from RUN_Class c where c.id=s.classId );
select * from RUN_Student s where exists ( select 1 from RUN_Class c where c.id=s.classId );
select * from RUN_Student s where exists ( select 'X' from RUN_Class c where c.id=s.classId ); 

show variables like "%sort%";
-- sort_buffer_size = 256MB
select 262144/1024;
-- max_length_for_sort_data = 4MB
select 4096/1024;


-- 查看是否开启慢SQL日志
show variables like "%slow_query_log%";
-- slow_query_log=1:慢SQL日志是否开启的开关
-- slow_query_log_file=/usr/local/mysql/data/cmmMacPro-slow.log:慢SQL存储的位置
set global slow_query_log = 0;
set global slow_query_log = 1;


-- long_query_time:默认是10s
show variables like "%long_query_time%";
set global long_query_time=3;
set global long_query_time=10;
show global variables like "%long_query_time%";

-- 模拟慢SQL
select sleep(1);
select sleep(4);

-- 查询慢SQL执行的次数:系统健康度检查指标
show global status like "%Slow_queries%";


-- mysql本身提供了慢SQL查询工具:mysqldumpslow
help "%mysqldumpslow%";

-- 进入到 mysql的bin目录后,执行命令:cmmMacPro:bin root# 
mysqldumpslow -s t -t 5 /usr/local/mysql/data/cmmMacPro-slow.log
/** 结果是:
Reading mysql slow query log from /usr/local/mysql/data/cmmMacPro-slow.log
Count: 3  Time=6.67s (20s)  Lock=0.00s (0s)  Rows=1.0 (3), root[root]@localhost
  select sleep(N)
Died at /usr/local/mysql/bin/mysqldumpslow line 162, <> chunk 2.
**/

-- mysqldumpslow 常用命令如下:
-- 耗时最多的5个sql语句:
mysqldumpslow -s t -t 5 /usr/local/mysql/data/cmmMacPro-slow.log;

-- 访问次数最多的5个sql语句:
mysqldumpslow -s c -t 5 /usr/local/mysql/data/cmmMacPro-slow.log;

-- 返回记录集最多的5个sql语句:
mysqldumpslow -s r -t 5 /usr/local/mysql/data/cmmMacPro-slow.log;

-- 按照时间返回前5条里面含有左连接的sql语句:
mysqldumpslow -t 5 -s t -g "left join" /usr/local/mysql/data/cmmMacPro-slow.log;

/**
参数说明:
-s:按照何种方式排序
c:记录次数
t:时间
l:查询时间
r:返回的记录数
ac at al ar 表示相应的倒序
-t:top n的意思
-g:后面可以写一个正则匹配模式,大小写不敏感
**/


-- 1 新建部门表Wind_Dept
create table Wind_Dept(
id int unsigned not null auto_increment,
deptno mediumint unsigned not null default 0, /*部门编号*/
dname varchar(20) not null default "",
loc varchar(13) not null default "",
PRIMARY KEY (`id`)
)engine=innodb default charset=utf8mb4 comment='部门表';

-- 2 新建员工表Wind_Emp
create table Wind_Emp(
id int unsigned not null auto_increment,
empno mediumint unsigned not null default 0, /*编号*/
ename varchar(20) not null default "", /*姓名*/
job varchar(9) not null default "", /*工作*/
mgr mediumint unsigned not null default 0, /*上级编号*/
hiredate date not null, /*入职时间*/
sal decimal(7,2) not null, /*薪水*/
comm decimal(7,2) not null, /*红利*/
deptno mediumint unsigned not null default 0, /*部门编号*/
PRIMARY KEY (`id`)
)engine=innodb default charset=utf8mb4 comment='员工表';

drop table Wind_Dept;
drop table Wind_Emp;
select * from Wind_Dept;
select * from Wind_Emp;

/**
简单介绍一下,当二进制日志启用后,这个变量就会启用。
它控制是否可以信任存储函数创建者,不会创建写入二进制日志引起不安全事件的存储函数。
如果设置为0(默认值),用户不得创建或修改存储函数,除非它们具有除CREATE ROUTINE或ALTER ROUTINE特权之外的SUPER权限。
设置为0还强制使用DETERMINISTIC特性或READS SQL DATA或NO SQL特性声明函数的限制。 
如果变量设置为1,MySQL不会对创建存储函数实施这些限制。 此变量也适用于触发器的创建。
那么为什么MySQL有这样的限制呢? 
因为二进制日志的一个重要功能是用于主从复制,而存储函数有可能导致主从的数据不一致。
所以当开启二进制日志后,参数log_bin_trust_function_creators就会生效,限制存储函数的创建、修改、调用。那么此时如何解决这个问题呢?set global log_bin_trust_function_creators=1;
**/
#开启可以创建存储函数的权限
show variables like "%log_bin_trust_function_creators%";
set global log_bin_trust_function_creators=0;
set global log_bin_trust_function_creators=1;


select * from Wind_Dept;
select * from Wind_Emp;

select now();
select now() from dual;

-- (1)创建一个函数:随机产生一个字符串
delimiter $$
create function ran_string(n int) returns varchar(255)
begin
	declare chars_str varchar(100) default 'abcdefghijklmnopqrstuvwxyz';
	declare return_str varchar(255) default '';
	declare i int default 0;
	while i < n do
		set return_str = concat(return_str,substring(chars_str,floor(1+rand()*52),1));
		set i=i+1;
	end while;
	return return_str;
end $$

-- (2)创建一个函数:随机产生部门编号 100-110
delimiter $$
create function rand_num() returns int(5)
begin
	declare i int default 0;
	set i=floor(100+rand()*10);
	return i;
end $$

-- (3)创建一个存储过程
-- (3.1)创建往Wind_Emp表中插入数据的存储过程
delimiter $$
create procedure insert_emp(in start int(10),in max_num int(10))
begin
declare i int default 0;
-- 把MySQL默认的自动提交关闭
set autocommit = 0;
repeat
set i = i+1;
insert into Wind_Emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values((start+i),ran_string(6),'salesman',0001,curdate(),2000,400,rand_num());
until i=max_num
end repeat;
commit;
end $$

-- (3.2)创建往Wind_Demp表中插入数据的存储过程
delimiter $$
create procedure insert_dept(in start int(10),in max_num int(10))
begin
declare i int default 0;
set autocommit = 0;
repeat
set i = i+1;
insert into Wind_Dept(deptno,dname,loc) values((start+i),ran_string(10),ran_string(8));
until i=max_num
end repeat;
commit;
end $$

show variables like "%autocommit%";

-- (4)调用存储过程
-- (4.1)插入部门表
call insert_dept(100,10);
select * from Wind_Dept;


-- (4.2)插入员工表
call insert_emp(100001,500000);
select * from Wind_Emp;


show global status like "%Slow_queries%";
-- long_query_time:默认是10s
show variables like "%long_query_time%";
set global long_query_time=3;
set global long_query_time=10;
show global variables like "%long_query_time%";

show variables like "%pro%";
show variables like "%profiling%";
set profiling=1;
show variables like "profiling";

desc Wind_Emp;
select * from Wind_Dept;
select * from Wind_Emp;
select * from Wind_Emp e join Wind_Dept d on e.deptno=d.deptno where e.name like "b%" group by empno order by id;
select * from Wind_Emp e join Wind_Dept d on e.deptno=d.deptno where e.ename like "b%" order by e.empno desc limit 400000;
select * from Wind_Emp e left join Wind_Dept d on e.deptno=d.deptno;
select * from Wind_Emp e right join Wind_Dept d on e.deptno=d.deptno;

select * from Wind_Emp group by id%10 limit 150000;
select id from Wind_Emp group by id%20  order by 5;

select id from Wind_Emp;
select * from Wind_Emp where id=1000;

-- SQL执行的详细信息和对应的编号
show profiles;

show profile cpu, block io for query 22;
show profile cpu, block io for query 78;

show variables like 'datadir';
show variables like "%sql_mode%";
-- 原始值:ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION
set global sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';


-- 全局日志查询是否开启,默认是关闭的(最好不要代开使用!)。
-- 日志文件 general_log_file:/usr/local/mysql/data/cmmMacPro.log
show variables like "%general_log%";
set global general_log=1;
set global general_log=0;
set global log_output="TABLE";
-- 执行SQL在线下复现慢查询场景
select * from Wind_Dept;
-- MySQL本身自带的数据库mysql,自带的表general_log(偷偷的把查询SQL记录一下)
select * from mysql.general_log;


-- 【表级锁分析--建表SQL】
create table mylock(
 id int not null primary key auto_increment,
 name varchar(20)
)engine myisam;
 
insert into mylock(name) values('a');
insert into mylock(name) values('b');
insert into mylock(name) values('c');
insert into mylock(name) values('d');
insert into mylock(name) values('e');
 
select * from mylock;
 
-- 【手动增加表锁】
lock table 表名字1 read(write),表名字2 read(write),其它;
lock table mylock read,Test write;
-- 【查看哪些表上被加锁了】
show open tables;
-- 【释放表锁】
unlock tables;
-- 查看变量 Table_locks_immediate和Table_locks_waited
show status like "table%";

show variables like 'tx_isolation';
show variables like 'transaction_isolation';

show status like 'innodb_row_lock%';
select * from information_schema.INNODB_TRX;
select * from information_schema.INNODB_TRX\G;


-- Mac 中命令行启动、停止、重启Mysql
-- 启动:sudo /usr/local/mysql/support-files/mysql.server start
-- 停止:sudo /usr/local/mysql/support-files/mysql.server stop
-- 重启:sudo /usr/local/mysql/support-files/mysql.server restart




SELECT MAX(id) FROM Wind_Dept;
show variables like "%unsafe_for_binlog%";
show variables like "%log_statements_unsafe_for_binlog%";

show index from RUN_Class;
select * from RUN_Class;

-- 看看有哪些session,这些session在做什么事情
show processlist;

-- 查看MDL锁
select * from performance_schema.metadata_locks;

SELECT * FROM performance_schema.setup_instruments;

select m.*,t.PROCESSLIST_ID from performance_schema.metadata_locks m left join performance_schema.threads t on m.owner_thread_id=t.thread_id;

select * from performance_schema.events_statements_current;

-- 在MySQL5.7及以后版本,performance_schema库中新增了metadata_locks表,专门记录MDL的相关信息。首先要开启MDL锁记录,执行如下SQL开启:
select * from performance_schema.setup_instruments WHERE NAME = 'wait/lock/metadata/sql/mdl';
UPDATE performance_schema.setup_instruments SET ENABLED = 'YES', TIMED = 'YES' WHERE NAME = 'wait/lock/metadata/sql/mdl';

show variables like "%lock_wait_timeout%";

show variables like "%innodb_autoinc_lock_mode%";
set global innodb_autoinc_lock_mode=1;

select last_insert_id();

/** 
目前在MySQL中锁相关的视图如下:
information_schema.innodb_trx:记录事务相关的信息,包括事务开始时间、事务SQL、事务权重(死锁发生时,回滚事务参考的权值)等。
information_schema.innodb_locks:记录事务持有锁的信息,包括事务持有的锁类型、被锁的表等。
information_schema.innodb_lock_waits:记录事务等待情况,每个事务被哪些事务所阻塞。
死锁情况可通过 show engine innodb status 查看。
**/

show engine innodb status;
select * from information_schema.innodb_trx;
select * from information_schema.innodb_locks;
select * from information_schema.innodb_lock_waits;

use information_schema;
use RUNOOB;

-- JVM内存分析工具:Jprofiler下载地址:https://www.ej-technologies.com/products/jprofiler/overview.html
-- 激活码:https://blog.csdn.net/fzy629442466/article/details/95454744
-- JVM系列篇:深入详解JVM内存模型与JVM参数详细配置:https://www.jianshu.com/p/895deef15808
-- JVM性能优化 (一) 初识JVM:https://www.jianshu.com/p/e598eecc1be9
-- Java虚拟机(JVM)的方法区(Method Area)存储了什么内容:https://www.breakyizhan.com/javamianshiti/2839.html
-- sql性能优化:https://www.jianshu.com/p/1d072b9b30bd
-- 微服务架构及分布式事务解决方案:https://www.cnblogs.com/rinack/p/9734551.html


select * from RUN_User;

-- 获取全部数据中薪水最高的
select max(salary) from RUN_User;

-- 通过性别进行分组,获取每组中薪水最高的
select sex, max(salary) from RUN_User group by sex;

-- 通过性别进行分组,获取每组中薪水之和
select sex, sum(salary) from RUN_User group by sex;

-- 时间大于2020-06-07,通过性别进行分组,获取每组中薪水之和
select sex, max(salary) from RUN_User where addTime>="2020-06-07 00:00:00" group by sex;

-- 时间大于2020-06-07,通过性别进行分组,获取每组中薪水之和(要求每组中的成员数大于等于3个的时候才统计)
select sex, max(salary) from RUN_User where addTime>="2020-06-07 00:00:00" group by sex having count(*)>=3;


show variables like "%optimizer_switch%";
/**
index_merge=on,index_merge_union=on,index_merge_sort_union=on,index_merge_intersection=on,engine_condition_pushdown=on,index_condition_pushdown=on,mrr=on,mrr_cost_based=on,block_nested_loop=on,batched_key_access=off,materialization=on,semijoin=on,loosescan=on,firstmatch=on,duplicateweedout=on,subquery_materialization_cost_based=on,use_index_extensions=on,condition_fanout_filter=on,derived_merge=on,use_invisible_indexes=off,skip_scan=on
**/


show create table mylock;

select 24117248/1024;

-- 8.0.17。5.7.21-21-log。5.7.31
SELECT version();
show variables like "%innodb_buffer_pool_size%";
select 134217728/1024/1024;

-- mysql下载官网:https://dev.mysql.com/downloads/mysql/


show index from RUN_Employee;
select * from RUN_Employee;
explain
select employeeId,employeeName,employeeSex,departmentId from RUN_Employee where DepartmentId=1;

show variables like "%optimizer_switch%";
/**
index_merge=on,index_merge_union=on,index_merge_sort_union=on,
index_merge_intersection=on,engine_condition_pushdown=on,
index_condition_pushdown=on,mrr=on,mrr_cost_based=on,
block_nested_loop=on,batched_key_access=off,materialization=on,
semijoin=on,loosescan=on,firstmatch=on,duplicateweedout=on,
subquery_materialization_cost_based=on,use_index_extensions=on,
condition_fanout_filter=on,derived_merge=on,use_invisible_indexes=off,skip_scan=on

-- 隐藏索引功能指标设置
use_invisible_indexes=off
use_invisible_indexes=on
**/


show databases;
use RUNOOB;

select * from RUN_Student;
update RUN_Student set name=replace(name,'"haochide"','haochide') where id in (1,2,3);


show variables like "%isolation%";
set session transaction isolation level read uncommitted;
set session transaction isolation level read committed;
set session transaction isolation level repeatable read;
set session transaction isolation level serializable;

-- MySQL 如何获得当前会话的TRX_ID 事务ID:
SELECT TRX_ID FROM INFORMATION_SCHEMA.INNODB_TRX  WHERE TRX_MYSQL_THREAD_ID = CONNECTION_ID();



use RUNOOB;
show tables;
select * from RUN_Class;
show create table RUN_Class;

CREATE TABLE `RUN_Class` (
  `Id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID(班级)',
  `ClassName` varchar(256) NOT NULL COMMENT '班级名称',
  `Status` tinyint(4) NOT NULL DEFAULT '1' COMMENT '有效=1,无效=-1',
  `AddTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '添加时间',
  `UpdateTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COMMENT='班级信息表'


-- 关于 MySQL LEFT JOIN 你可能需要了解的三点 
drop table RUN_Product;
create table ASM_Product(
ID int(11) unsigned not null auto_increment comment '主键ID',
Amount int(11) unsigned default null comment '数量',
PRIMARY KEY(ID)
)ENGINE=InnoDB CHARSET=utf8mb4 COMMENT='产品表'

create table ASM_ProductDetails(
ID int(11) unsigned not null auto_increment comment '主键ID',
Weight int(11) unsigned default null comment '重量',
Exist int(11) unsigned default null comment '是否有库存',
PRIMARY KEY(ID)
)ENGINE=InnoDB CHARSET=utf8mb4 COMMENT='产品详细信息表'

insert into ASM_Product(Amount) values (100),(200),(300),(400);
select * from ASM_Product;
insert into ASM_ProductDetails(ID, Weight,Exist) values (2,22,0),(4,44,1),(5,55,0),(6,66,1);
select * from ASM_ProductDetails;

select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID;

-- ON 子句和 WHERE 子句有什么不同?
-- 一个问题:下面两个查询的结果集有什么不同么?
select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID and pd.ID=2;
select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID where pd.ID=2;

-- 再来看一个示例:
select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID and p.Amount=100;
-- 再来看一个示例:
select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID and p.Amount=200;

-- 我们可以把 IS NULL 子句 看作是否定匹配条件。
select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID and pd.Weight!=44 and pd.Exist=0
where pd.ID is null;

select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID and pd.Weight!=44 and pd.Exist=1
where pd.ID is null;

select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID 
where pd.ID is null or pd.Weight=44 or pd.Exist!=0;

select * from ASM_Product p left join ASM_ProductDetails pd on p.ID=pd.ID 
where pd.ID is null or pd.Weight=44 or pd.Exist=0;



select * from RUN_User;
show global variables like 'wait_timeout';
select version();

CREATE TABLE `RUN_Account` (
  `Id` int(20) NOT NULL AUTO_INCREMENT COMMENT '用户Id',
  `Name` varchar(32) NOT NULL DEFAULT '' COMMENT '姓名',
  `Money` int(20) NOT NULL DEFAULT 0 COMMENT '账户余额',
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='账户表';

insert into RUN_Account(name,money) values ("lucy",1000);
insert into RUN_Account(name,money) values ("marry",1000);
select * from RUN_Account;



 

おすすめ

転載: blog.csdn.net/cmm0401/article/details/111398507