union

union  合并2条或者多条语句的结果

语法

sql1 union sql2

mysql> select goods_id,goods_name,shop_price from goods where shop_price <30
    -> union
    -> select goods_id,goods_name,shop_price from goods where shop_price >4000;

可以从两张表查询然后再union  因为  union是合并的结果集,与哪张表无关

 

如果两个语句的列名名称不一样,一样能取出来数据,会以第一个sql的语句列名为准

mysql> select goods_id,goods_name,shop_price from goods where shop_price <30
    -> union
    -> select cat_id,goods_name,market_price from goods where shop_price >4000;
+----------+-----------------------+------------+
| goods_id | goods_name            | shop_price |
+----------+-----------------------+------------+
|        5 | 索爱原装M2卡读卡器                  |      20.00 |
|       26 | 小灵通/固话20元充值卡              |      19.00 |
|       30 | 移动20元充值卡                 |      18.00 |
|        3 | 多普达Touch HD             |    7198.80 |
+----------+-----------------------+------------+

如果取出的字段的数量不相等的时候,union是不能使用的,两个sql语句的字段必须相等才能用union

 

如果列的类型不一致,同样也可以使用,但是类型不一致,没有什么意义,在开发中不会遇到

 

union后的结果集仍然可以再次排序    合并出来的还是结果集若以能用 order by 排序

mysql> select goods_id,goods_name,shop_price from goods where shop_price <30
    -> union
    -> select cat_id,goods_name,market_price from goods where shop_price >4000;
    ->order by shop_price asc;

 

注意

内层的order by 语句单独使用时不会影响结果集,在执行期间就被mysql的代码分析器给优化掉了

内层的order by 必须能够影响结果集时,才有意义,比如,配合limit 使用

mysql> select cat_id,goods_name,shop_price from goods
    -> where cat_id =4____________________如果在此sql语句只单单加order by 会被优化掉
    -> union
    -> select cat_id,goods_name,shop_price from goods where cat_id=5 ______如果在此sql语句只单单加order by 会被优化掉 
    -> order by shop_price asc;

必须能够影响结果集时,比如配合limit 使用时  如下

mysql> (select cat_id,goods_name,shop_price from goods where cat_id =4 order by shop_price
 asc limit 2)
    -> union
    -> (select cat_id,goods_name,shop_price from goods where cat_id =3 order by shop_price
 asc limit 3);

其中为了防止分析器误判的发生,单层语句最好加上() 比如,如果不加()最后面的 order by shop_price limit 3 就会被认为是相对于整句来说的

 

如果union 后的结果有重复 (即某几行所有的列值都一样)

这种情况是比较常见,默认会去重(即合并)

如不想去重 就用union all   代替  union 即不会再去重

posted @ 2013-11-25 02:09  long896130895  阅读(249)  评论(0)    收藏  举报