1. 程式人生 > >SQL中UNION和UNION ALL的詳細用法

SQL中UNION和UNION ALL的詳細用法

在開發中,有些資料的儲存可能涉及到分庫分表,查詢的時候,可能需要查詢所有的分表,這個時候,就需要用到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>