SQL数据分析学习(三)—mysql必知必会

236 阅读6分钟

1.mysql的优点:代码开源免费使用、执行快、易于安装使用。
2.选定使用某数据库:use 数据库名
3.显示

show databases;可用库              
show tables;可用表
show columns from customers;可用列

4.SELECT语句:

select * from products limit 5;结果限制5行
select * from products limit 5,5;结果从第5行开始限制5行
select * from products limit 5 offset 5;结果同上

select product.name from shop.products;完全限制数据库的表名和列名

5.where和order by:

1.前者在order by 之前。   
2.条件写法:
where... between... and...
where...or/and...
where...(not) in (...)
where...like...'%...'/'%_'

6.正则表达式

select name from products where name regexp binary 'Pack 1000|2000';找到name中出现过1000的,与like不同,binary区分大小写,|——>or

select name form products where name regexp '[123] Ton' order by name;
匹配[]内部+Ton的内容,[]相当于or,也可以表示为[1|2|3] Tom;
匹配数字:[1-9]
匹配字母:[a-z]
特殊字符(.、-)用\\做前导:\\.和\\-
匹配字符类:[:alnum:]、[:alpha:]、[:blank:]、[:cntrl:]、[:digit:]、[:graph:]、[:lower:]、[:lower:]、[:print:]、[:punct:]、[:space:]、[:upper:]、[:xdigit:]
匹配实例:*(0或多个)、+(1或多个)、?(0或1个)、{n}(指定个数)、{n,}(不少于指定个数)、{n,m}(数目范围)

select name from products where name regexp '\\([0-9] sticks?\\)' order by name;
或:[[:digit:]]{3}——>[0-9][0-9][0-9]

定位符:^(开始)、$(结尾)、[[:<:]](词的开始)、[[:>:]](词的结尾)
^[0-9\\.]:查找.或数字开头的字符串

7.创建计算字段

select concat(vend_name,'(',vend_country,')') from vendors order by vend_name;创建字段vend_name(vend_country)用concat连接列值

rtrim去掉值右边的空格,ltrim、trim
as在select列名后赋予别名
left():返回左边字符,right
length():返回字符串长度
locate():找出一个子串
lower():小写转换
upper():大写转换
soundex():返回soundex值,发音比较
substring():返回子串字符

select cust_name,cust_contact
from customers
where soundex(cust_name)=soundex('Y Lie');Lie错误输入为Lee时匹配发音值

8.日期时间部分

date(字段名)和time(字段名)在仅需要日期或时间的时候使用,datetime是定义的数据类型,存储日期和时间值——'YYYY-MM-DD hh:mm:ss。

查找月份订单2种方法:
where date(order_date) between '2005-09-01' and '2005-09-30';

where year(order_date)=2005 and month(order_date)=9;

9.聚合函数

group by必须在where之后,having和order by 之前。

select id,count(*) from products group by id with rollup;使用rollup得到每个分组及分组级别的值。
select * from *
where 列条件
group by 列名
having 组条件

10.子查询

子查询进行过滤:
select...from...where...(子查询)
select...(子查询) as...from...

11.表的联结

select vend_nme,prod_name,prod_price
from vendors,products
where vendors.vend_id=products.vend_id order by vend_name,prod_name;where指定联结条件或者进行过滤,无where条件时返回的是笛卡尔积
内部联结:inner join...on...
自联结:p1.id=p2.id and p2.id='DTNTR'
表别名只用于查询,列别名可以返回客户主机。

12.组合查询

select...from...where...
union
select... from...where...
或者:
select...from...where...or...
union自动去除重复行,不去重要用union all;order by只能在末尾用1次

13.全文本搜索
14.插入数据

insert into 表名(...) values(...);插入单行
insert into 表名 values(...),(...);插入多行
insert into...select... from...;插入查询的数据

15.创建表:

create table customers(
cust_id int not null auto_increment,
...) engine=InnoDB;auto_increment通常用于分配id被索引,且作为主键,每个表只能有1个,获取:
select 1645766;
not null default 1:没给出数量时默认1

16.更新删除

update 表名 set 列名=值;更新值
alter table 表名 add 列名 字段描述;添加列
alter table 表名 drop column 列名;删除列
alter table 表名 change 旧列名 新列名 新数据类型;
alter table 表名 modify 列名 新类型;

定义外键:
alter table 表名
add constraint ... foreign key(...) references 表名(列名)

17.创建视图

视图主要用于数据检索:经常需要某种格式的结果又不必在每次需要时执行联结。
视图不能更新的情况:分组、联结、子查询、并、聚合函数、distinct

18.存储过程

建立:
cerate procedure productpricing()
begin
    select avg(price) as priceaverage
    from products
end;

执行(调用):
call productpricing(@pricelow,@pricehigh,@priceaverage);调用productpricing存储过程,并返回最低价、最高价和均价,但不显示。
删除:
drop procedure productprice;

使用参数:
create procedure productpricing(
    out pl decimal(8,2),
    out ph decimal(8,2),
    out pa decimal(8,2)
)
begin
    select min(price)
    into pl
    from products;
    select max(price)
    into ph
    from products;
    select avg(price)
    into pa
    from products;
end;关键字out指出参数存储值

显示:select @priceaverage;
创建有输入参数的:
create procedure ordertotal(
    in onumber int,
    out ototal decimal(8,2)
)
begin 
    select sum(item_price*quantity)
    from orderitems
    where order_num=onumber
    into ototal;
end;

call ordertotal(20005,@total);

select @total;


建立智能存储过程:
--name:ordertotal
--parameters:onumber=order number
-------------taxable=0 if not taxable,1 if taxable
-------------ototal=order total variable

create procedure ordertotal(
    in onumber int,
    in taxable boolean,
    out ototal decimal(8,2)
) commet 'obtain order total,optionally adding tax'
begin

--declare variable for total
declare total decimal(8,2);
--declare tax percentage
declare taxable int default 6;

--get the order total
select sum(item_price*quantity)
from orderitems
where order_num=onumber
into total;

--is this taxable?
if taxable then
--yes,add taxrate to the total
    select total+(total/100*taxrate) into total;
end if;
    select total into ototal;
    
end;

调用:call ordertotal(20005,0,@total);
select @total;

检查存储过程:
show create procedure ordertotal;
show procedure status like 'ordertotal';用like限制输出

19.使用游标

创建游标ordernumbers:
create proceddure processorders()
begin
    --创建
    declare ordernumbers cursor
    for
    select order_num from orders;
    --打开游标
    open ordernumbers;
    --使用游标数据
    fetch ordernumbers into o;
    
    --关闭
    close ordernumbers;
end;

循环检索:
create proceddure processorders()
begin
    declare done boolean default 0;
    declare o int;
    
    declare ordernumbers cursor
    for 
    select order_num from orders;
    
    declare continue handler for sqlstate '02000' set done=1;
    
    open ordernumbers;
    
    repeat
    
        fetch ordernumbers into o;
        
    until done end repeat;
    
    close ordernumbers;
end;
步骤:
声明done默认值为0和o变量存储order_num
创建游标ordernumbers
声明sqlstate出现‘02000’时done=1结束
打开游标
循环检索直至结束
关闭游标

游标存储过程:
create proceddure processorders()
begin
    declare done boolean default 0;
    declare o int;
    declare t decimal(8,2);
    
    declare ordernumbers cursor
    for
    select order_num from orders;
    declare continue handler for sqlstate '02000' set done=1;
    
    create table if not exists ordertotals(order_num int,total decimal(8,2));
    
    open ordernumbers;
    
    repeat
        fetch ordernumbers into o;
        
        call ordertotal(o,l,t);
        
        insert into ordertotals(order_num,total) values(o,t);
        
        until done end repeat;
        
        close ordernumbers;
    end;

20.触发器

delete/insert/update语句后自动执行,仅支持表;每个表最多支持6个触发器;1个触发器不能与多个事件或表关联。

create trigger newproduct after insert on products for each row select 'product added';触发器名newproduct,返回'product added'

drop trigger newproduct;

create trigger deleteorder before delete on orders
for each row
begin
    insert into archive_orders(order_num,order_date,cust_id) values(old.order_num,old.order_date,old.cust_id);
end;

create trigger updatevendor before update on vendors for each row set new.vend_state=upper(new.vend_state);

21.事务处理

事务transaction
回退rollback
提交commit
保留点savepoint
创建占位符:
savepoint delete;
回退到保留点:
rollback to delete;
更改默认的提交行为:
set autocommit=0;

字符集:

show character set;
show collation;

管理用户:

use mysql;
select user from user;

创建用户账号:
create user ben identified by 'p@?w0rd';口令
重命名账号:
rename user ben to bforta;
删除:
drop user bforta;

设置访问权限:
show grants for bforta;显示权限
grant select on crashcourse.* T0 bforta;允许用户bforta在crashcourse数据库所有表上使用select
show grants for bforta;

撤销权限:
revoke select on crashcourse.* from bforta;

层次控制:
grant/revoke all;
on database.*;
on database.table;

更改用户口令:
set password for bforta=password('n3wp@?w0rd');

set password=password('n3wp@?w0rd');

数据库维护:

analyze table orders;检查表键是否正确
check table orders,orderitems;

22.补充

if、ifnull、is not null函数:
if(expr1,expr2,expr3);满足expr1则返回expr2,否则expr3
ifnull(expr1,expr2);null则返回expr2,否则expr1,判断空值
isnull(expr);null则返回1,否则0

cast(变量 as 数据类型):数据类型转换,如考试成绩

name='李%'判断符
name like '李%'匹配符,计数