mysql union 详解

Union:
作用:把2次或多次查询结果合并起来
要求:两次查询的列数一致
推荐:查询的每一列,相对应的列类型也一样

可以来自于多张表

多次sql语句取出的列名可以不一致,此时,以第1个sql的列名为准

例一、

select user_name,user_email,msg_content from ecs_feedback where msg_status = 1 union select user_name,email,content from ecs_comment where status = 1;

mysql union 详解

如果不同的语句中取出的行,有完全相同(每个列的值都相同),那么相同的行将会合并(去重复)
如果不去重复,可以加all来指点
如果子句中有order by,limit,必须加()把句子括起来    order by推荐放到所有子句之后,即--对最终合并后的结果来排序
例:

例二、

(select  goods_id,cat_id,goods_name,shop_price from goods where cat_id=4) union (select goods_id,cat_id,goods_name,shop_price from goods where cat_id=5) order by shop_price desc;

mysql union 详解

例三、

(select  goods_id,cat_id,goods_name,shop_price from goods where cat_id=4 order by shop_price desc) union (select goods_id,cat_id,goods_name,shop_price from goods where cat_id=5 order by shop_price desc);

mysql union 详解

此时看图可以看出并没有实现排序  但是不会报错,所以说在自己中order by要想正常使用必须配合limit  这样才能实现排序  如果order by不配合limit使用,会被语法分析器优化分析时去掉

例四:

(select goods_id,cat_id,goods_name,shop_price from goods where cat_id=3 order by shop_price desc limit 3) union (select goods_id,cat_id,goods_name,shop_price from goods where cat_id=4 order by shop_price desc limit 2);

mysql union 详解

可见此时order by起作用

原文地址:http://blog.csdn.net/huangjianxiang1875/article/details/7876153

上一篇:haproxy json 自定义格式日志 并用rsyslog 收集


下一篇:Git&Github基本操作与分支管理