SQL中UNION和UNION ALL的详细用法

UNION操作符用于合并两个或多个SELECT语句的结果集,这里需要注意的是:UNION内部的SELECT语句必须拥有相同数量的

列,列也必须拥有相似的数据类型,同时,每条SELECT语句中列的顺序必须相同。

UNION语法:

[sql]  view plain  copy
  1. SELECT column_name(s) FROM table_name1  
  2. UNION  
  3. SELECT column_name(s) FROM table_name2  

union操作符合并的结果集,不会允许重复值,如果允许有重复值的话,使用UNION ALL.

UNION ALL语法:
[sql]  view plain  copy
  1. SELECT column_name(s) FROM table_name1  
  2. UNION ALL  
  3. SELECT column_name(s) FROM table_name2  
UNION结果集中的列名总等于union中第一个select语句中的列名。

这里我就不举例子说明,重点总结下我在项目开发中遇到的问题:1、由于需要合并十个select语句,写法上需要用到sql中<foreach>;.2、在写sql语句是,用到了order by,要用括号区分开,要不会报错。

sql语句写法:

[sql]  view plain  copy
  1. <select id="getFourteenHotPost" parameterType="map" resultMap="productCommentsInfoAndroid">  
  2.         select t.comments_id,t.product_id,t.comment,t.order_path from (  
  3.         <foreach collection="tableNames" item="item" separator="UNION ALL">  
  4.             (SELECT c.comments_id,c.product_id,c.comment,i.order_path,c.p_index,c.t_index,c.title,c.time   
  5.             FROM ${item} as c left join `gshop_comments_img` as i on c.comments_id = i.comments_id    
  6.             where c.object_type=2 and c.display=1 and c.is_show=1   
  7.             and c.t_index=1   
  8.             GROUP BY c.product_id ORDER BY c.p_index asc,c.t_index desc,c.title desc,c.time desc limit 14)    
  9.         </foreach>) t  
  10.         GROUP BY t.product_id ORDER BY t.p_index asc,t.t_index desc,t.title desc,t.time desc limit 14  
  11.     </select>  

猜你喜欢

转载自blog.csdn.net/qq_15037231/article/details/80612252