MySQL高级(进阶) SQL 语句二
Posted 呼噜呼噜懒洋洋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL高级(进阶) SQL 语句二相关的知识,希望对你有一定的参考价值。
1.create view
视图,可以被当作是虚拟表或存储查询。
视图跟表格的不同是,表格中有实际储存数据记录,而视图是建立在表格之上的一个架构,它本身并不实际储存数据记录。
临时表在用户退出或同数据库的连接断开后就自动消失了,而视图不会消失。
视图不含有数据,只存储它的定义,它的用途一般可以简化复杂的查询。
比如你要对几个表进行连接查询,而且还要进行统计排序等操作,写sql语句会很麻烦的,
用视图将几个表联结起来,然后对这个视图进行查询操作,就和对一个表查询一样,很方便。
语法: create view "视图表名" as "select 语句";
create view v_region_sales as select a.region region,sum(b.sales) sales from location a
inner join store_info b on a.store_name = b.store_name group by region;
select * from v_region_sales;
drop view v_region_sales;
2.union----联集
将两个sql语句的结果合并起来,两个sql语句所产生的字段需要是同样的数据记录种类
union:生成结果的数据记录值将没有重复,且按照字段的顺序进行排序
语法: [select 语句1] union [select 语句2] ;
union all:将生成结果的数据记录值都列出来,无论有无重复
语法: [select 语句1] union all [select 语句2];
select store_name from location union select store_name from store_info;
select store_name from location union all select store_name from store_info;
3.交集值
取两个SQL语句结果的交集
select a.store_name from location a inner join store_info b on a.store_name = b.store_name;
select a.store_name from location a inner join store_info b using (store_name);
#两表其中的一个表没有指定的行,而另一个表这个行有重复不适用,要求两个表确实有交集的行的时候用
select a.store_name from
(select store_name from location union all select store_name from store_info) a
group by a.store_name having count(*) > 1;
#取两个SQL语句结果的交集,且没有重复
select a.store_name from (select b.store_name from location b inner join store_info c on b.store_name = c.store_name) a
group by a.store_name;
select distinct a.store_name from location a inner join store_info b using (store_name);
select distinct store_name from location where (store_name) in (select store_name from store_info);
select distinct a.store_name from location a left join store_info b using (store_name) where b.store_name is not null;
左/右连接取交集( 左/右表取没出现NULL值的行),distinct去重
4.无交集值
显示第一个sql语句的结果, 且与第二个sql语句没有交集的结果,且没有重复
select distinct store_name from location where (store_name) not in (select store_name from store_info);
select distinct a.store_name from location a left join store_info b using (store_name) where b.store_name is null;
select a.store_name from
(select distinct store_name from location union all select distinct store_name from store_info) a
group by a.store_name having count(*) = 1;
5.case
是sql用来做为 if-then-else 之类逻辑的关键字
语法:
select case ("字段名")
when "条件1" then "结果1" .
when "条件2" then "结果2"
...
[else "结果n"]
end
from "表名";
# "条件"可以是一个数值或是公式。 else 子句则并不是必须的。
select store_name, case store_name
when los angeles then sales * 2
when boston then 1000
else sales
end
"new sales",date
from store_info;
#"new sales" 是用于以上是关于MySQL高级(进阶) SQL 语句二的主要内容,如果未能解决你的问题,请参考以下文章