建表语句
set names utf8mb4;
use f_algo_platform;
CREATE TABLE `result_table` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键id',
`prec` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '准确率',
`acc` DOUBLE NOT NULL DEFAULT 0 COMMENT '精确率',
`model_path` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '模型存储地址',
PRIMARY KEY (`id`),
UNIQUE KEY `uniq_task_id` (`task_id`)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '算法结果表';
CREATE TABLE `billboard_theme` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT '规则id',
`task_id` bigint(20) NOT NULL COMMENT '任务id',
`strategy_id` bigint(20)NOT NULL COMMENT '投放策略id',
`name` varchar(32) NOT NULL DEFAULT '' COMMENT '主题名称',
`brief_name` varchar(32) NOT NULL DEFAULT '' COMMENT '简短的主题名称',
`business_type` int(11)NOT NULL COMMENT '业务类型',
`billboard_type` int(11)NOT NULL COMMENT '榜单类型',
`top_img` varchar(256) NOT NULL DEFAULT '' COMMENT '头图',
`recommendation` varchar(32) NOT NULL DEFAULT '' COMMENT '推荐语',
`brief_recommendation` varchar(32) NOT NULL DEFAULT '' COMMENT '简短的推荐语',
`priority` int(11)NOT NULL COMMENT '优先级,越小越靠前',
`platform` int(11)NOT NULL COMMENT '平台',
`share_title` varchar(32) NOT NULL DEFAULT '' COMMENT '分享标题',
`share_slogan` varchar(64) NOT NULL DEFAULT '' COMMENT '分享语',
`share_pic` varchar(64) NOT NULL DEFAULT '' COMMENT '分享图片',
`status` int(11) NOT NULL DEFAULT '0' COMMENT '状态,2未上线,3已上线,4已下线',
`creator` varchar(32) NOT NULL DEFAULT '' COMMENT '创建人mis',
`updater` varchar(32) NOT NULL DEFAULT '' COMMENT '更新人mis',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
KEY `idx_strategy_id` (`strategy_id`),
KEY `idx_task_id` (`task_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='榜单主题';
DQL查询语句
show databases ;
show tables ;
use myemployees;
select * from employees;
select * from departments;
select * from locations;
select * from jobs;
show columns from employees;
desc employees;
进阶1:基础查询
#1.查询表中单个字段
select last_name from employees;
#2.查询表中的多个字段
select last_name,email from employees;
select
employee_id,
first_name,
last_name,
phone_number
from employees;
# 3.使用着重号
select
`employee_id`,
`first_name`,
`last_name`,
`phone_number`
from employees;
#4.查询表中所有的字段
select * from employees;
#5.查询常量值
select 100 from employees;
select 'john';
#6.查询表达式
select 100%98;
#7.查询函数
select version();
#8.为字段取别名
#方法一
select 100%98 as 结果;
select last_name as 姓 from employees;
#方法二
select last_name 姓 from employees;
#案例 查询salary显示结果为output
select salary as 'out put' from employees;
#9.去重
select department_id from employees;
select distinct department_id from employees;
#10.+号的作用-当作运算符
#案例:查询员工的姓名链接成一个字段,合并显示为姓名
select last_name+first_name '姓名'from employees; #没有结果
select 100+90;
select '100'+88; #会将字符串转换成为数值型,转换成功就继续做加法运算,
select '哈哈'+98; #如果转换失败就将字符转换为0,
select null+98; #如果有一个为null。则结果为null
#11.字符串的拼接
select concat(last_name,first_name) '姓名' from employees;
#12.ifnull函数
select ifnull(commission_pct,0) '奖金率' from employees;
进阶2 条件查询
#1.按条件表达式进行筛选
select * from employees where salary>12000;
select last_name,department_id from employees where department_id!=90;
select last_name,department_id from employees where department_id<>90;
#2.按逻辑表达式筛选,将多条件链接在一起
select last_name,salary,commission_pct from employees where salary>10000 and salary<20000;
select * from employees where department_id<90 or department_id>110 or salary>15000;
select * from employees where not(department_id>=90 and department_id<=110) or salary>15000;
#3.like模糊查询
select * from employees where last_name like '%a%';
select last_name,salary from employees where last_name like '__n_l%';
select first_name,last_name,salary from employees where last_name like '_\_%'; #使用转义字符
select first_name,last_name,salary from employees where last_name like '_a_%' escape 'a'; #将a指明为转义字符
#4.between and
select first_name,last_name,department_id from employees where department_id between 0 and 100;
#5.in
select * from employees where job_id in ('IT_PROG','AD_VP','AD_PRES');
#4.is null
select first_name,last_name,commission_pct from employees where commission_pct is null ;
select first_name,last_name,commission_pct from employees where commission_pct is not null ;
#5.安全等于
select first_name,last_name,commission_pct from employees where commission_pct <=> null ;
select first_name,last_name,commission_pct from employees where commission_pct <=> 0.2 ;
进阶3 排序查询
select * from employees order by salary;
select * from employees order by salary desc;
select * from employees order by salary asc;
select * from employees where department_id >= 90 order by hiredate asc;
select salary*12*(1+ifnull(commission_pct,0)) 年薪 from employees order by 年薪 desc;
select last_name,salary from employees order by length(last_name) desc,salary;
select last_name,salary,employee_id from employees order by salary,employee_id desc;
select last_name,department_id,salary*12*(1+(ifnull(commission_pct,0))) 年薪 from employees order by 年薪 desc,last_name;
select last_name,salary from employees where not (salary between 8000 and 17000) order by salary desc ;
select * from employees where email like '%e%' order by length(email) desc,department_id asc;
进阶4 常见函数
#字符函数
#1.length()获取参数值的字节数
select length('join');
select length('张三丰');
#2.concat()拼接字符串
select concat(last_name,'-',first_name) 姓名 from employees;
#3.upper,lower
select upper(last_name) from employees;
select lower(first_name) from employees;
select concat(upper(last_name),'_',lower(first_name)) from employees;
#4.substr,substring截取字符串
select substr('去哪儿网度假部门',5,2);
select substr(last_name,1,2) ,last_name from employees;
select concat(upper(substr(last_name,1,1)),lower(substr(last_name,2))) from employees;
#5.instr返回字串在字符串中的索引
select instr('去哪儿网','网') as output;
select instr('去哪儿网','xie') as output;
#6.trim 去除空格,只取出首尾的空格
select trim(' aa bb ') as output;
select trim('a' from 'aaaaaaaaaaaaaaa你好aaaaa') as output;
#7.lpad ,rpad 用指定的字符填充字符串至指定的长度
select lpad('因叔叔',10,'*') as output;
# 8.replace替换
select replace('张无忌爱上了周至若','周至若','赵敏') as output;
#数学函数
#1.round 四舍五入,取整数
select round(1.45);
select round(1.5678,2); #小数点后取两位
#2.ceil 向上取整
select ceil(1.002);
#3,floor向下取整
select floor(1.999);
#truncate 截断
select truncate(1.9999,1);
#mod取余
select mod(10,3);
select mod(10,-3);
#日期函数
#1.now()返回当前的系统时间
select now();
#2.curdate()返回当前系统的日期,不包括时间
select curdate();
#3,curtime()返回当前系统的时间,不包括日期
select curtime();
#4,获取指定的时,分,秒
select YEAR(2020-11-11);
#5,str_to_date
select str_to_date('9-13-1999','%m-%d-%Y');
select date_format('1999-6-12','%Y-%m-%d');
# 其他函数
select version();
select database();
select user();
#流程控制函数
#1.if函数 s实现if else的效果
select if(10>5,'大','小');
select last_name,if(commission_pct is null,'you','wu') from employees;
#2.case函数的使用
#使用一
select salary 原始工资,department_id,
case department_id
when 50 then salary*2
when 60 then salary*1.2
when 70 then salary*1.3
else salary
end 新工资
from employees;
#使用二
select salary,
case
when salary > 10000 then 'A'
end
from employees;
select now();
select employee_id,last_name,salary,salary*1.2 from employees;
select length(last_name),substr(last_name,1,1) 首字符,last_name from employees order by 首字符;
select concat(last_name,'earns',salary,'monthly but wants',salary*3 ) from employees;
select job_id,
case job_id
when 'AD_PRES' then 'A'
when 'AD_VP' then 'B'
when 'IT_PROG' then 'C'
end
from employees;
#分组函数
#1,简单使用
select sum(salary) 工资总和 from employees;
select round(avg(salary)) 平均值,min(salary) 最小值,max(salary) 最大值 ,count(salary) 总数 from employees;
#2,参数类型支持
select sum(last_name),avg(last_name) from employees;
select max(hiredate),min(hiredate)from employees;
#3,可以和distinct搭配使用,去重
select sum(distinct(salary)) from employees;
select count(distinct salary) from employees;
#4,count函数的详细介绍
select count(salary) from employees;
select count(*) from employees;
select count(1) from employees; #相当于在表中加了一列常量
#5,和分组函数一同查询的字段有限制,同分组查询的字段一般要求是group by之后的字段
select avg(salary),employee_id from employees; #错误
select datediff(now(),'1995-09-15');
select count(*) from employees where department_id=90;
进阶5 分组查询
select department_id,avg(salary) from employees group by department_id;
select max(salary),job_id from employees group by job_id;
select count(*),location_id from departments group by location_id;
#添加筛选条件,分组前的筛选
select avg(salary) ,department_id from employees where email like '%a%' group by department_id;
select max(salary),manager_id from employees where commission_pct is not null group by manager_id;
#添加复杂的筛选条件
#select department_id,count(*) '员工数' from where '员工数'>2 employees group by department_id;
#根据已查询的结果进行再次查询分组
select count(*) ,department_id from employees group by department_id having count(*)>2;
select job_id,max(salary) from employees where commission_pct is not null group by job_id having max(salary)>200;
select min(salary) 最低工资,manager_id from employees where manager_id>102 group by manager_id having 最低工资>5000 order by manager_id;
#gruopby 按表达式进行分组
select count(*),length(last_name) from employees group by length(last_name) having count(*) >5 order by length(last_name);
#按多个字段进行分组
select department_id,job_id from employees group by department_id, job_id order by department_id ;
select department_id,job_id,avg(salary) from employees group by department_id,job_id;
select max(salary)-min(salary) difference from employees;
select min(salary),manager_id from employees where manager_id is not null group by manager_id having min(salary)>6000;
select department_id,count(*),avg(salary)from employees group by department_id order by avg(salary);
进阶6 链接查询
#发生笛卡尔乘积现象
select name,boyName from beauty,boys;
select name ,boyName from beauty,boys where beauty.boyfriend_id=boys.id;
1,等值链接
select boyName ,name from boys,beauty where beauty.boyfriend_id=boys.id;
use myemployees;
select * from departments;
#查询员工名和对应的部门名
select last_name ,department_name from employees e,departments d where e.department_id=d.department_id;
#查询员工号,工种号,工种名
#注意,其别名之后不能够再使用表明
select * from jobs;
select e.last_name,e.job_id,j.job_title from employees e,jobs j where e.job_id=j.job_id;
#可以加筛选
select last_name,department_name,commission_pct from employees e,departments d where e.department_id=d.department_id and e.commission_pct is not null;
#查询城市名中第二个字符为o的部门名和城市名
select * from departments;
select d.department_name,l.city from departments d,locations l where d.location_id=l.location_id and l.city like '_o%';
#加分组
#查询每一个城市的部门个数
select count(*) 部门数,city from departments d,locations l where d.location_id=l.location_id group by l.city;
#查询有奖金的每个部门的部门名和部门的领导编号和该部门的最低工资
select
d.department_name,min(salary)
from departments d,employees e
where
d.department_id=e.department_id and e.commission_pct is not null
group by d.department_name;
#加排序
select job_title,count(*) from jobs j,employees e where j.job_id=e.job_id group by job_title order by count(*) desc ;
#三表链接
select last_name,department_name,city from employees e,departments d,locations l where e.department_id=d.department_id and d.location_id=l.location_id;
2,非等值链接
select last_name,salary,grade_level from employees e,job_grades j where e.salary>j.lowest_sal and e.salary <j.highest_sal;
#自链接,自己链接自己
select e1.last_name,e2.last_name from employees e1,employees e2 where e1.manager_id=e2.employee_id;
3,内连与外连
#1.内链接
select last_name,department_name from employees e inner join departments d on e.department_id=d.department_id;
select last_name,job_title from employees e inner join jobs j on e.job_id = j.job_id where last_name like '%e%';
select city,count(*) from departments d inner join locations l on d.location_id = l.location_id group by d.location_id having count(*)>3;
select department_name,count(*) 员工数 from departments d inner join employees e on d.department_id = e.department_id group by e.department_id having count(*)>3 order by count(*)desc;
select last_name,department_name,job_title from employees e inner join departments d on e.department_id = d.department_id inner join jobs j on e.job_id = j.job_id order by department_name desc;
#非等值链接
select last_name,salary,grade_level from employees e inner join job_grades j on e.salary>j.lowest_sal and e.salary<j.highest_sal;
select last_name,salary,grade_level from employees e inner join job_grades j on e.salary between j.lowest_sal and j.highest_sal;
select e.last_name,e.employee_id,m.last_name,m.employee_id from employees e inner join employees m on e.manager_id=m.employee_id;
#2.外链接
use girls;
select * from beauty;
select be.*,bo.* from beauty be left outer join boys bo on be.boyfriend_id=bo.id;
use myemployees;
select d.*,e.* from departments d left join employees e on d.department_id = e.department_id where employee_id is null ;
#全外链接
use girls;
#交叉链接=笛卡尔乘积
select b.*,bo.* from boys b cross join beauty bo;
select be.*,b.*from beauty be left join boys b on be.boyfriend_id=b.id where be.id>3;
use myemployees;
select city,d.* from departments d right join locations l on d.location_id = l.location_id where d.department_id is null;
select last_name,department_name from departments d left join employees e on d.department_id = e.department_id where d.department_name='SAL' or d.department_name='IT' and last_name != null;
进阶7 子查询
#一,where,having后面
#1.标量子查询
select
last_name,salary
from
employees
where
salary>=(select salary from employees where last_name='Abel')
order by
last_name;
select
last_name,job_id,salary
from employees
where job_id=(
select job_id
from employees
where employee_id=141)
and salary> (
select salary
from employees
where employee_id=143
);
select last_name,job_id,salary
from employees
where salary = (
select min(salary)
from employees
);
select department_id,min(salary)
from employees
group by department_id
having min(salary)>(
select min(salary)
from employees
where department_id=50
);
#2.列子查询(多行子查询)
select last_name,department_id from employees where department_id in (select distinct department_id from departments where location_id in (1400,1700));
select last_name,employee_id,job_id,salary from employees where salary <any(select distinct salary from employees where job_id='IT_PROG') and job_id!='IT_PROG';
#3.行子查询
select * from employees where (employee_id,salary)=(select min(employee_id),max(salary) from employees);
#二,放在select后面
select d.*,(select count(*) from employees e where e.department_id=d.department_id) 个数 from departments d;
select (select department_name from departments d where d.department_id=e.department_id)from employees e where employee_id=102;
#三,放在from后面
select j.grade_level,avgsalary.* from (select avg(salary) 平均工资,department_id from employees group by department_id) avgsalary,job_grades j where avgsalary.平均工资>j.lowest_sal and avgsalary.平均工资<j.highest_sal;
#四,放在exist后面
#,exist的使用,判断查询是否有值
select exists(select employee_id from employees);
select department_name from departments d where exists(select * from employees e where e.department_id=d.department_id);
进阶8,分页查询
select * from employees limit 0,5;
select * from employees limit 10,15;
select * from employees where commission_pct is not null order by salary desc limit 10;
进阶9 联合查询union联合查询
#查询部门编号>90或者邮箱包含a的员工的信息
select * from employees where email like '%a%'
union
select * from employees where department_id>90;
DML语言
进阶1 插入语句
#1.插入beauty
use girls;
insert into beauty (id,name,sex,borndate,phone,photo,boyfriend_id) values (13,'唐艺昕','女','1990-4-23','18988888888',null,2);
select * from beauty;
delete from beauty where id=16;
#2.可以为null的列是如何插入值的,不可以为null的列必须有值
#方式二,可以为空的列,可以不用写
insert into beauty (id,name,sex,borndate,phone,boyfriend_id) values (14,'金星','女','1990-4-23','13822222222',9);
#3.列的顺序是否可以颠倒
insert into beauty (name,sex,id,phone) values ('将昕','女',16,'1345678903');
#4.列数与值的个数必须一致
#5.可以省略列名,默认所有列,而且列的顺序与表中列的顺序一致
insert into beauty values (18,'张飞','男',null,'12345678901',null,null);
#方式二
insert into beauty set id=19,name='刘涛',phone='34567654839';
insert into beauty (id,name,sex,borndate,phone,photo,boyfriend_id)
values (20,'唐艺昕','女','1990-4-23','18988888888',null,2),
(21,'唐艺昕','女','1990-4-23','18988888888',null,2),
(22,'唐艺昕','女','1990-4-23','18988888888',null,2),
(23,'唐艺昕','女','1990-4-23','18988888888',null,2);
insert into beauty (id,name,phone) select 26,'宋茜','12345678901';
进阶2 修改语句
#1.修改单表的记录
update beauty set phone='13899888899' where name like '唐%';
select * from beauty;
#2.修改boys
update boys set boyName='张飞',userCP=20 where id=2;
#2.修改多表的记录
#2.修改多表的记录
update boys b
inner join beauty be
on b.id=be.boyfriend_id
set be.phone=11111111111
where b.boyName='张无忌';
select * from beauty;
update beauty be left join boys b on be.boyfriend_id=b.id set be.boyfriend_id=2 where b.id is null;
#删除语句
#方式一
#单表的删除
delete from beauty where phone like '%9';
select * from beauty;
#多表的删除
delete be from beauty be inner join boys b on be.boyfriend_id=b.id where b.boyName='张无忌';
delete be,b from beauty be inner join boys b on be.boyfriend_id=b.id where be.name='Angelababy';
#方式二 truncate清空数据
truncate table boys;
#delete 与truncate的区别
use myemployees;
CREATE TABLE my_employees(
Id INT(10),
First_name VARCHAR(10),
Last_name VARCHAR(10),
Userid VARCHAR(10),
Salary DOUBLE(10,2)
);
CREATE TABLE users(
id INT,
userid VARCHAR(10),
department_id INT
);
#2. 显示表my_employees的结构
DESC my_employees;
#方式一:
INSERT INTO my_employees
VALUES(1,'patel','Ralph','Rpatel',895),
(2,'Dancs','Betty','Bdancs',860),
(3,'Biri','Ben','Bbiri',1100),
(4,'Newman','Chad','Cnewman',750),
(5,'Ropeburn','Audrey','Aropebur',1550);
INSERT INTO users
VALUES(4,'Rpatel',10),
(5,'Bdancs',10);
update my_employees set Last_name='drelxer' where id=3;
update my_employees set Salary =1000 where Salary<900;
delete my,u from my_employees my inner join users u on my.Userid = u.userid where u.userid='Bbiri';
select * from my_employees;
DDL语言
#一,库的管理
#if not exists
create database if not exists books;
show databases ;
#库的修改
alter database books character set gbk;
#库的删除
drop database if exists books;
#表的管理
#1.表的创建
create database if not exists books;
create table book(
id int, #编号
bName varchar(20), #s书名
price double,
authorId int,
publishDate datetime #出版日期
);
desc book;
create table author(
id int,
authorName varchar(20),
nation varchar(10)
);
desc author;
#2.表的修改
#修改列名
alter table book change column publishDate pubDate DATETIME;
desc book;
#修改列的类型
alter table book modify column pubDate timestamp;
desc book;
#添加新列
alter table author add column annual double;
#删除列
alter table author drop column annual;
#修改表名
alter table author rename to bookAuthor;
alter table bookAuthor rename to author;
#3表的删除
drop table if exists book;
show tables ;
#通用的写法
drop database if exists 旧库名;
drop table if exists 旧表名;
#表的复制
insert into author
(id,authorName,nation)
values
(1,'村上春树','日本'),
(2,'莫言','中国'),
(3,'风谈','中国'),
(4,'金庸','中国');
#1.仅仅复制表的结构
create table cpoyAuthor like author;
select * from copyAuthor2;
#2,复制表的结构家数据
create table copyAuthor2 select * from author;
#3.只复制部分数据
create table capyAuthor3 select id,authorName from author where nation='中国';
#4.仅仅复制某些字段
create table copyAuthor4 select id,authorName from author where 1=2;
create database if not exists test;
use test;
create table dept1(
id int(7),
name varchar(20)
);
#2,将表departments中的数据插入的dept1中
create table dept2 select department_id,department_name from myemployees.departments;
create table emp5(
id int(7),
first_name varchar(20),
last_name varchar(20),
dep_id int(7)
);
alter table emp5 modify column last_name varchar(50);
create table employees2 like myemployees.my_employees;
drop table if exists emp5;
alter table employees2 rename to emp5;
alter table emp5 add column test_column varchar(20);
alter table test.emp5 drop column test_column;
select * from emp5;
#1。整型,如何设置无符号与有符号 unsigned
create table tabInt(
t1 int(9) zerofill,
t2 int(9) unsigned
);
select * from tabInt ;
insert into tabInt (t1) values (12);
insert into tabInt (t1) values (-12);
insert into tabInt (t2) values (-1);
insert into tabInt (t2) values (1);
drop table if exists tabInt;
insert into tabInt values (3563333333,333333567);
#3.小数
create table tab_float(
f1 float(5,2),
f2 double(5,2),
f3 decimal(5,2)
);
select * from tab_float;
insert into tab_float values(123.45,123.56,123.67);
insert into tab_float values(1234.456,123.56,123.67);
insert into tab_float values(123.456,123.567,123.678);
insert into tab_float values(123.4,123.56,123.67);
#三,字符型
create table tab_char(
c1 enum('a','b','c','d')
);
select * from tab_char;
insert into tab_char (c1) values ('a');
insert into tab_char (c1) values ('e');
insert into tab_char (c1) values ('A');
create table tab_set(
c1 set('a','b','c')
);
insert into tab_set (c1) values ('a');
insert into tab_set (c1) values ('a,b');
insert into tab_set (c1) values ('a,e');
create table tab_date(
t1 datetime,
t2 timestamp
);
insert into tab_date values (now(),now());
insert into tab_date values ('2020-02-04','2020-02-04');
select * from tab_date;
show variables like 'time_zone';
set time_zone ='+9:00'
约束,主键与外键
#1,创建表添加越约束
#1.添加列级约束
create database if not exists students;
use students;
drop table if exists stuinfo;
create table stuinfo(
id int primary key, #主键
stuNmae varchar(20) not null,
gender char(1),
searnum int unique ,
age int default 18
);
desc stuinfo;
select * from stuinfo;
#查看表中的索引,主键,外健,唯一约束会创建索引
show index from stuinfo;
drop table if exists major;
create table major(
id int primary key ,
majorNmae varchar(20)
)default character set utf8;
#添加表级约束
drop table if exists stuinfo;
create table stuinfo(
id int,
stuName varchar(20),
gender char(1),
seat int,
age int,
majorid int,
constraint pk primary key(id),#主键
constraint uq unique (seat), #唯一键
constraint fk_stuinfo_major foreign key(majorid) references major(id)
);
show index from stuinfo;
create table stuinfo(
id int,
stuName varchar(20),
gender char(1),
seat int,
age int,
majorid int,
primary key(id),#主键
unique (seat), #唯一键
foreign key(majorid) references major(id)
);
create table if not exists stuinfo(
id int primary key ,
stuName varchar(20) not null ,
gender char(1),
seat int unique ,
age int default 18,
majorid int,
constraint fk_stuinfo_major foreign key(majorid) references major(id)
) default character set utf8;
select * from stuinfo;
insert into stuinfo (id,stuName,seat) values (1,'tom',null),
(2,'john',null);
create table if not exists stuinfo(
id int,
stuName varchar(20) not null unique default '张三',
gender char(1),
seat int unique ,
age int default 18,
majorid int,
constraint pk primary key (id,stuName),
constraint fk_stuinfo_major foreign key(majorid) references major(id)
);
insert into stuinfo (id,stuName,seat) values (1,'tom',null),
(2,'tom',null);
#修改表时,添加约束
drop table if exists stuinfo;
desc stuinfo;
create table if not exists stuinfo(
id int,
stuName varchar(20),
gender char(1),
seat int ,
age int ,
majorid int
);
use students;
#1.添加非空约束
alter table stuinfo modify column stuName varchar(20) not null ;
#2.删除非空约束
alter table stuinfo modify column stuName varchar(20) null;
#3.添加默认约束
alter table stuinfo modify column age int default 18;
#4.添加主键
#列级约束
alter table stuinfo modify column id int primary key ;
#表级约束
alter table stuinfo add constraint primary key (id);
#5.添加唯一
use students;
alter table stuinfo modify column seat int unique ;
alter table students.stuinfo add constraint unique (seat);
#6.添加外健
alter table students.stuinfo add foreign key (majorid) references major(id);
alter table students.stuinfo add constraint fk foreign key (majorid) references major(id);
#三,修改表时删除约束
#1.删除非空约束
alter table stuinfo modify column stuName varchar(20) null;
#2.删除默认约束
alter table stuinfo modify column age int ;
#3.删除主键
alter table stuinfo drop primary key ;
#4.删除唯一约束
alter table stuinfo drop index fk;
#5.删除外健约束
alter table stuinfo drop foreign key fk;
show index from stuinfo;
desc stuinfo;
#标识列
#一,创建表时设置标识列
drop table if exists tab_identity;
create table tab_identity(
id int ,
name varchar(20)
);
select * from tab_identity;
insert into tab_identity values (1,'john');
insert into tab_identity values (2,'tom');
insert into tab_identity (name) values ('wede');
insert into tab_identity values (20,'james');
#1.不从一开始
show VARIABLES like '%auto_increment%';
#修改表时设置标识列
alter table tab_identity modify column id int primary key auto_increment;
事物
show variables like 'autocommit';
#事物的演示
drop table if exists account;
create table account(
id bigint unsigned comment 'id',
username varchar(20) comment '用户姓名',
balance decimal(40, 20) comment '存款'
)character set utf8;
alter table account default character set utf8;
alter table account modify column id bigint unsigned primary key auto_increment;
insert into account (username,balance) values ('aa',1000),('赵敏',1000);
select * from account;
#开启事物
set autocommit =0;
update account set balance=300 where username='张无忌';
start transaction ;
update account set balance=500 where username='张无忌';
update account set balance=1500 where username='赵敏';
#commit;
rollback ;
#事物没有隔离性
#查看隔离级别
select @@tx_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; #可避免脏读,不可重复读,幻读
#savepoint 结点名 设置回滚点
use students;
select * from account;
set autocommit =0;
start transaction ;
delete from account where id=5;
savepoint a;
delete from account where id =6;
rollback to a;
视图,虚拟的表
desc students.stuinfo;
select * from students.stuinfo;
select * from major;
insert into
students.stuinfo
values
(1,'张飞','男',111,18,1),
(2,'刘备','男',112,18,2),
(3,'关羽','男',113,18,1),
(4,'赵云','男',114,18,2),
(5,'黄盖','男',115,18,1);
set character set utf8;
show variables like '%char%';
set character_set_database=utf8;
set character_set_server =utf8;
set character_set_connection =utf8;
set character_set_filesystem =utf8;
insert into major (id,majorNmae) values (1,'语文'),(2,'数学');
select s.stuName,majorNmae from stuinfo s inner join major m on s.majorid=m.id where s.stuName like '张%';
create view v1 as select s.stuName,majorNmae from stuinfo s inner join major m on s.majorid=m.id where s.stuName like '张%';
select * from v1 where stuName='张飞';
一,创建视图
use myemployees;
create view
myv1
as select
e.last_name,department_name,job_title
from employees e
inner join departments d on e.department_id=d.department_id
inner join jobs j on e.job_id = j.job_id;
二,使用视图
select * from myv1;
select last_name,department_name,job_title from myv1 where last_name like '%a%';
drop view avgsalary;
create view avgsalary as select avg(salary) avs,department_id from employees group by department_id;
select avs, j.grade_level from avgsalary a inner join job_grades j on a.avs>j.lowest_sal and a.avs<j.highest_sal ;
select avs,department_id from avgsalary order by avs desc limit 1;
create view myv3 as select avs,department_id from avgsalary order by avs desc limit 1;
select avs,department_name from avgsalary a inner join departments d on a.department_id = d.department_id order by a.avs desc limit 1;
select avs,department_name from myv3 m inner join departments d on m.department_id = d.department_id;
三,视图的修改
select * from myv3;
create or replace view myv3 as select avg(salary) avs,job_id from employees group by job_id;
#四,删除视图
#五,查看视图
desc myv3;
show create view myemployees.myv3;
drop view emp_v1;
create view emp_v1 as select last_name,salary,email from employees where phone_number like '011%';
select * from emp_v1;
create or replace view emp_v2
as select max(salary),department_name
from employees e inner join departments d on e.department_id = d.department_id
group by e.department_id having max(salary) >12000;
select * from emp_v2;
#六,视图的更新
create or replace view myv1 as select last_name,email,salary*12*(1+ifnull(commission_pct,0)) asalary from employees;
create or replace view myv1 as select last_name,email from employees;
#1.插入数据
select * from myv1;
insert into myv1 values ('张飞','ZF@qq.com');
#2.修改
update myv1 set last_name='张无忌' where last_name='张飞';
#3.删除
delete from myv1 where last_name='张无忌';
#可以为视图添加只读权限
create or replace view myv1 as select max(salary) m,department_id from employees group by department_id;
update myv1 set m=9000 where department_id=10;
#常量视图
create or replace view myv2 as select 'john' name;
update myv2 set name='jack';
#select 中包含子查询
create or replace view myv3 as select (select max(salary) from employees) '最高工资';
update myv3 set 最高工资=100000;
#join语句不能更新
#from 后是一个不能更新的视图
#演示delete
create table if not exists bookType(
id int auto_increment,
type varchar(20) not null ,
primary key (id)
);
use students;
create table book(
bid int primary key ,
bname varchar(20) unique not null ,
price float default 10,
btype_id int ,
constraint foreign key fk_book_booktype(btype_id) references bookType(id)
);
insert into bookType values(1,'aaaa');
set autocommit =0;
insert into book (bid, bname,price, btype_id) values (1,'it',12.34,1);
create view bookview as select bname,type from book b inner join bookType bT on b.btype_id = bT.id where b.price>1000;
#create or replace view bookview as
#alter view bookview as select
#级联更新或级联删除
drop table if exists major;
create table major(
id int primary key ,
majorName varchar(20)
)default character set utf8;
show index from major;
insert into major values (1,'java'),(2,'h5'),(3,'data');
drop table if exists stuinfo;
desc stuinfo;
create table if not exists stuinfo(
id int,
stuName varchar(20),
gender char(1),
seat int ,
age int ,
majorid int
)default character set =utf8;
show index from stuinfo;
#添加外健
alter table stuinfo add constraint fk_stu_major foreign key(majorid) references major(id);
insert into
stuinfo
values
(1,'john1','女',null,null,1),
(2,'john2','女',null,null,2),
(3,'john3','女',null,null,1),
(4,'john4','女',null,null,2),
(5,'john5','女',null,null,3),
(6,'john6','女',null,null,1);
#删除专业表的3号专业
use students;
#方式一:级联删除,删除主表会将从表进行删除
show create table students.stuinfo;
alter table stuinfo drop foreign key fk_stu_major;
alter table stuinfo add constraint fk_stu_major foreign key(majorid) references students.major(id) on delete cascade ;
select * from students.major;
select * from students.stuinfo;
delete from students.major where id=4;
#方式二:级联置空
alter table stuinfo drop foreign key fk_stu_major;
alter table stuinfo add constraint fk_stu_major foreign key(majorid) references students.major(id) on delete set null;
select * from students.major;
select * from students.stuinfo;
delete from major where id =2;
变量
set @name=100;
select count(*) into @count from students.major;
select @count ;
set @m=1;
set @n=2;
set @sum = @m+@n;
select @sum;
declare m int default 1;
declare n int default 2;
declare sum int;
set sum =n+m;
select sum;
储存过程和函数
#1.空参列表
use girls;
drop table admin;
create table admin(
id bigint unsigned auto_increment,
username varchar(20) not null,
password varchar(20) not null,
primary key (id)
)default character set = utf8;
insert into
admin (id,username,password)
values
(1,'join',8888),
(2,'lyt',6666);
select * from admin;
delimiter $
create procedure myp1()
begin
insert into admin(username,password) values ('john2',0000),('jack',0000),('tom1',0000);
end $
call myp1()$
#in模式的参数的存储过程
create procedure myp2(in name varchar(20))
begin
select bo.* from boys bo right join beauty b on b.boyfriend_id=bo.id where b.name=name;
end $
call myp2('柳岩') $
create procedure myp3(in username varchar(20),in password varchar(20))
begin
declare result varchar(20) default '';
select count(*) into result from admin where admin.username=username and admin.password=password;
select result;
end $
create procedure myp5(in username varchar(20),in password varchar(20))
begin
declare result int;
select count(*) into result from admin where admin.username=username and admin.password=password;
select if(result>0,'成功','失败');
end $
call myp5('张飞',0000) $
#创建带out模式的存储过程
create procedure myp7(in girlname varchar(20),out boyname varchar(20))
begin
select bo.boyName into boyname from boys bo inner join beauty b on bo.id=b.boyfriend_id where b.name=girlname;
end $
select * from beauty;
select * from boys;
set @name='' $
call myp7('柳岩',@name) $
select @name;
call myp7('柳岩',@name1) $
select @name1;
#4.带inout模式的存储模式
create procedure myp8(inout a int,inout b int)
begin
set a=a*2;
set b=b*2;
end $
set @a=10 $
set @b=20 $
call myp8(@a,@b) $
select @a,@b;
create procedure test1(in user varchar(20),in psas varchar(20))
begin
insert into admin (admin.username,admin.password) values (username,password);
end $
call test1('aaa','0000');
select * from admin;
create procedure test2(in id int,out name varchar(20),out phone varchar(20))
begin
select b.name,b.phone into name,phone from beauty b where b.id=id;
end $
#存储过程的删除
drop procedure test1;
#查看存储过程的信息
show create procedure myp2;
create procedure test3(in mydate datetime,out strdate varchar(50))
begin
select date_format(mydate,'%Y年%m月%d日') into strdate;
end $
call test3(now(),@str);
select @str;
函数
#一,函数的创建语法
#调用语法
#无参无返回
use myemployees;
create function myf1() returns int
begin
declare c int default 0;
select count(*) into c from employees;
return c;
end $
select myf1()$
#有参有返回
create function myf2(empNmae varchar(20)) returns double
begin
declare s double default 0;
set @sal=0;
select salary into s from employees where last_name=empNmae;
return s;
end $
select * from employees;
select myf2('Kochhar');
create function myf3(deptname varchar(20)) returns double
begin
declare sal double default 0;
select avg(salary) into sal from employees e inner join departments d on e.department_id=d.department_id where department_name=deptname;
return sal;
end $
select * from departments;
select myf3('IT');
#三,查看函数
show create function myf3;
#四,删除函数
drop function myf3;
create function myf4(num1 float,num2 float) returns float
begin
declare sum float;
set sum= num1+num2;
return sum;
end $
select myf4(1.3,1.4);
#流程控制结构
create procedure myf5(in score int)
begin
case
when score>=90 and score<=100 then select 'A';
when score>=80 and score<=90 then select 'b';
when score>=70 and score<=80 then select 'c';
when score>=60 and score<=70 then select 'd';
else select 'E';
end case ;
end $
call myf5(77);
create function myf6 (score int) returns char
begin
if score>=90 and score<=100 then return 'a';
elseif score>=80 and score<=90 then return 'b';
elseif score>=70 and score<=80 then return 'c';
end if;
end $
select myf6(77);
#循环结构
use girls;
create procedure pro_while1(in insertCount int)
begin
declare i int default 1;
while (i<=insertCount) do
insert into admin(username,password) values ('rose','6666');
set i=i+1;
end while ;
end $
drop procedure pro_while1;
call pro_while1(10)$
select * from admin;
create procedure pro_while2(in insertCount int)
begin
declare i int default 1;
a:while (i<=insertCount) do
insert into admin(username,password) values (concat('rose',i),'5555');
if i>=20 then leave a;
end if;
set i=i+1;
end while a;
end $
call pro_while2(111);