1>UNION 自动去除 重复数据,UNION ALL 不会
SELECT * FROM help_category t WHERE t.help_category_id<=7
UNION
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10 ;
结果:
<
|
SELECT * FROM help_category t WHERE t.help_category_id<=7
UNION ALL
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10 ;
结果:
<
|
2>顺序问题
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10
UNION
SELECT * FROM help_category t WHERE t.help_category_id<=7;
<
|
调换顺序后,结果无序
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10
UNION ALL
SELECT * FROM help_category t WHERE t.help_category_id<=7;
<
|
同样 ,调换顺序后结果无序
所以为了保证数据的有序,需要在 最后那个sql 中加上order by
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10
UNION ALL
SELECT * FROM help_category t WHERE t.help_category_id<=7 ORDER BY help_category_id;
<
|
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10
UNION
SELECT * FROM help_category t WHERE t.help_category_id<=7 ORDER BY help_category_id;
<
|
Union,对两个结果集进行并集操作,不包括重复行
Union All,对两个结果集进行并集操作,包括重复行
最后把所有的sql脚本保留一下
SELECT * FROM help_category t WHERE t.help_category_id<=7
UNION
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10 ;
SELECT * FROM help_category t WHERE t.help_category_id<=7
UNION ALL
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10 ;
--=================================================================================
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10
UNION
SELECT * FROM help_category t WHERE t.help_category_id<=7 ORDER BY help_category_id;
SELECT * FROM help_category t WHERE t.help_category_id<=7
UNION
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10 ORDER BY help_category_id;
--=================================================================================
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10
UNION ALL
SELECT * FROM help_category t WHERE t.help_category_id<=7 ORDER BY help_category_id;
SELECT * FROM help_category t WHERE t.help_category_id<=7
UNION ALL
SELECT * FROM help_category t WHERE t.help_category_id>=5 AND t.help_category_id<=10 ORDER BY help_category_id;