UNION

SQL UNION 操作符合并两个或多个 SELECT 语句的结果。

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

默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。

UNION 结果集中的列名总是等于 UNION 中第一个 SELECT 语句中的列名

SELECT country, name FROM Websites
WHERE country='CN'
UNION ALL
SELECT country, app_name FROM apps
WHERE country='CN'
ORDER BY country;
select country from websites union select country from apps;

--连接两个表的查询结果集,重复的不显示

select country from websites union all select country from apps order by country;

--连接俩个个表的查询结果集,显示重复

select country,name from websites where country = 'CN' union all 

select country,app_name from apps where country='CN' order by name; 

--通过where条件查询的结果,连接连个表的结果集,并根据名字排序。

使用UNION命令时需要注意,只能在最后使用一个ORDER BY命令,是将两个查询结果合在一起之后,再进行排序!绝对不能写两个ORDER BY命令。

另外,在使用ORDER BY排序时,注意两个结果的别名保持一致,使用别名排序很方便。当然也可以使用列数。

ORDER BY 除了可以对指定的字段进行排序,还可以使用函数进行排序:

order by abs(a);

ORDER BY 只能当前 SQL 查询结果进行排序,如要对 union all 出来的结果进行排序,需要先做集合。

select aa.* from 
(select country,name from websites where country = 'CN'
union all select country,app_name from apps where country='CN' ) aa
order by aa.name;
posted @ 2019-07-30 14:47  寒冰射手(电脑)  阅读(226)  评论(0编辑  收藏  举报