当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL union 语法代码示例分析

MySQL union 语法代码示例分析

2017年12月12日  | 移动技术网IT编程  | 我要评论
复制代码 代码如下:

select ...
union [all | distinct]
select ...
[union [all | distinct]
select ...]
select ... union [all | distinct] select ... [union [all | distinct] select ...]

union 用于把来自许多select语句的结果组合到一个结果集合中。 (如果你要将多个表的查询结果进行合并输出比如说 群组消息跟个人消息表是分离的但是想一起提取出来并显示的话就可以如此处理。通过mysqlunion联合查询出来即可)
列于每个select语句的对应位置的被选择的列应具有相同的类型(前提条件是两个select出来的列类型要保持一样的才行!)。(例如,被第一 个语句选择的第一列应和被其它语句选择的第一列具有相同的类型。)在第一个select语句中被使用的列名称也被用于结果的列名称。
select语句为常规的选择语句,但是受到如下的限定:
只有最后一个select语句可以使用into outfile。
high_priority不能与作为union一部分的select语句同时使用。如果您对第一个 select指定了high_priority,则不会起作用。如果您对其它后续的select语句指定high_priority,则会产生语法错 误。
如果您对union不使用关键词all,则所有返回的行都是唯一的,如同您已经对整个结果集合使用了distinct。如果您指定了all,您会从 所有用过的select语句中得到所有匹配的行。
distinct关键词是一个自选词,不起任何作用,但是根据sql标准的要求,在语法中允许采用。(在mysql中,distinct代表一个共 用体的默认工作性质。)
您可以在同一查询中混合union all和union distinct。被混合的union类型按照这样的方式对待,即distict共用体覆盖位于其左边的所有all共用体。distinct共用体可以使 用union distinct明确地生成,或使用union(后面不加distinct或all关键词)隐含地生成。
如果您想使用order by或limit子句来对全部union结果进行分类或限制,则应对单个地select语句加圆括号,并把order by或limit放到最后一个的后面。以下例子同时使用了这两个子句:
代码
(select a from tbl_name where a=10 and b=1)union(select a from tbl_name where a=11 and b=2)order by a limit 10;
(如果想要实现分页的话可以这样处理 将两个查询的结果集当作是一个大的结果集处理然后再对此大的结果集进行limit处理即可实现!)好好好 ~!
(select a from tbl_name where a=10 and b=1)mysqlunion(select a from tbl_name where a=11 and b=2)order by a limit 10;
这种order by不能使用包括表名称(也就是,采用tbl_name.col_name格式的名称)列引用。可以在第一个select语句中提供一个列别名,并在 order by中参阅别名,或使用列位置在order by中参阅列。(首选采用别名,因为不建议使用列位置。)
另外,如果带分类的一列有别名,则order by子句必须引用别名,而不能引用列名称。以下语句中的第一个语句必须运行,但是第二个会运行失败,出现在'order clause'中有未知列'a'的错误:
代码
复制代码 代码如下:

(select a as b from t) union (select ...) order by b;
(select a as b from t) union (select ...) order by a;
to apply order by or limit to an individual select,
place the clause inside the parentheses that enclose the select:
(select a as b from t) union (select ...) order by b;
(select a as b from t) union (select ...) order by a;
to apply order by or limit to an individual select,
place the clause inside the parentheses that enclose the select:

为了对单个select使用order by或limit,应把子句放入圆括号中。圆括号包含了select:
代码
复制代码 代码如下:

(select a from tbl_name where a=10 and b=1 order by a limit 10)
union(select a from tbl_name where a=11 and b=2 order by a limit 10);
(select a from tbl_name where a=10 and b=1 order by a limit 10)
union(select a from tbl_name where a=11 and b=2 order by a limit 10);

二 实例扩展
mysqlunion可以对同一个表的两次查询联合起来. 这样做的益处也非常明显, 比如在blog应用中, 可以利用一条sql语句实现置顶blog和普通blog的分页显示.
代码
复制代码 代码如下:

(
select *
from `blog`
where top=1
order by created desc
)
union (
select *
from `blog`
where top = 0
order by created desc
) limit 2 , 3

以上的相关内容就是对mysqlunion语法的介绍,望你能有所收获。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网