SQL中UNION和UNION ALL的详细用法

2023-05-16 08:17:50

在开发中,有些数据的存储可能涉及到分库分表,查询的时候,可能需要查询所有的分表,这个时候,就需要用到UNION或者UNION ALL,下面介绍一下UNION的用法以及与UNION ALL的区别:

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

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

UNION语法:

SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2

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

UNION ALL语法:
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UNION结果集中的列名总等于union中第一个select语句中的列名。

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

sql语句写法:

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



  • 作者:罗卜丝粉
  • 原文链接:https://blog.csdn.net/zouxucong/article/details/73468979
    更新时间:2023-05-16 08:17:50