(14)union
来源:互联网 发布:贴吧娘贴吧君分手知乎 编辑:程序博客网 时间:2024/06/04 00:30
一、union 联合
①作用:两次或者多次查询结果合并起来
②要求:两次查询的列数一致,查询的每一列,相对应的列类型也一样
③可以来自于多张表,多次sql语句取出的列名可以不一致,以取第一个sql的列名为准即可。
如果不同的语句中取出的行,有完全相同(每个列的值都相同)的行,那么相同的行将被合并(系统自动去重复)
如果要保留重复的行数据,应该用union all
drop table if exists ta;create table ta ( id char(1), num int);insert into ta values('a',5);insert into ta values('b',10);insert into ta values('c',15);insert into ta values('d',10);drop table if exists tb;create table tb ( id char(1), num int);insert into tb values('b',5);insert into tb values('c',10);insert into tb values('d',20);insert into tb values('e',99);//要求:将id相同的num加起来,不同表构成一张表(用union all),以免有重复的行select id,sum(num) from (select * from ta union all select * from tb)tmp group by id;
⑤如果子句中含有order by,limit需子句加(),推荐放到所有子句之后,即对最终的结果进行排序,下面演示的是同一张表中的数据,所以不存在相同的元组,所以用union即可
()union()
//将栏目4商品降序排序,将栏目5商品降序排序,合并select goods_id,goods_name,cata,shop_price from goods where cata=4 order by shop_price unionselect goods_id,goods_name,cata,shop_price from goods where cata=5 order by shop_price;(错误)//错误原因:取cata=5的商品时 用order by出现了歧义,可能是cata=4价格降序与cata=5合并之后对整体进行降序排序可能是cata=4价格降序与cata=5价格降序合并//解决方法1:加括号,提高优先级,这种可以将同个栏目的放在一起(select goods_id,goods_name,cata,shop_price from goods where cata=4 order by shop_price) union(select goods_id,goods_name,cata,shop_price from goods where cata=5 order by shop_price);//解决方法2:所有子句之后进行排序,相同栏目的不一定放在一起(select goods_id,goods_name,cata,shop_price from goods where cata=4 ) union(select goods_id,goods_name,cata,shop_price from goods where cata=5 )order by shop_price;//取第6个栏目前3的商品,取第4个栏目价格前2的商品,用union(select goods_id,goods_name,cata,shop_price from goods where cata=6 order by shop_price desc limit 3)union (select goods_id,goods_name,cata,shop_price from goods where cata=4 order by shop_price desc limit 2);
在子句中,order by配合limit使用才有意义,order by不配合limit使用,会被语法分析器优化分析时,去除。
比如将多个班级的同学,混合成一班同学按身高排序,对学生进行排序,就应该混合完后,再排序。若对每班级的学生进行排序,然后合并,没什么意义还是没序的状态,因为这个问题的重点在排序
比如将每个班级的前3身高的同学选出,这个问题的重点在选择每班的前3身高,重点不是排序,所以在子句中就可以选出,再合并
阅读全文
0 0
- (14)union
- Neo4j CQL -(14) -UNION联合
- union和union All的区别(union联合)
- hive union (all)
- 联合体(union)
- c++ union(联合体)
- 共用体(Union)
- Almost Union-Find ()
- 组合查询(Union)
- Union
- union
- union
- UNION
- union
- union
- union
- UNION
- union
- Hibernate基本知识概括
- 创建并运行一个基本的Python测试程序(自己的看法修改)
- POJ1904:King's Quest(强连通 & 二分图)
- XRecyclerview的XListView式的下拉刷新和上拉加载(改自XListView,修改比率低于30%,效果很好)
- mysql安装和Django 项目hello world创建
- (14)union
- Android 常见导致OOM的主要原因
- 关于GC的一些总结
- Unity 手势识别插件
- nexus start的时候报 wrapper | The nexus service was launched, but failed to start 2014-08-03 08:08 5182人
- Nginx根目录修改失效问题
- Spring框架的优点
- A
- 第一个freemarker程序