合并查询union

Posted bibiafa

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了合并查询union相关的知识,希望对你有一定的参考价值。

表union_a

CREATE TABLE `union_a` (
  `ID` int(11) NOT NULL AUTO_INCREMENT COMMENT 自增主键,
  `T_NAME` varchar(255) NOT NULL DEFAULT ‘‘ COMMENT 所在表名称,
  `NUMBER` int(11) NOT NULL DEFAULT 0 COMMENT 用于排序,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8

 

select * from union_a;
+----+--------+--------+
| ID | T_NAME | NUMBER |
+----+--------+--------+
|  1 | a      |    100 |
|  2 | a      |     28 |
|  3 | a      |     98 |
|  4 | a      |     19 |
|  5 | a      |    999 |
+----+--------+--------+

表union_b

create table union_b like union_a;

 

select * from union_b;
+----+--------+--------+
| ID | T_NAME | NUMBER |
+----+--------+--------+
|  1 | b      |     23 |
|  2 | b      |     76 |
|  3 | b      |     32 |
|  4 | b      |     43 |
|  5 | b      |     11 |
+----+--------+--------+

 

1.union每个子句都可以使用()包围,如果前面的子句用括号包围,则后面的子句必须用括号包围,如果后面的子句用括号包围,前面的子句不是必须要括号包围

(select * from union_a) union (select * from union_b);

或者

select * from union_a union (select * from union_b);

错误语法:

(select * from union_a) union select * from union_b;

 2.每个子句可以包含where子句

select * from union_a where number > 50 union select * from union_b where number< 30;
+----+--------+--------+
| ID | T_NAME | NUMBER |
+----+--------+--------+
|  1 | a      |    100 |
|  3 | a      |     98 |
|  5 | a      |    999 |
|  1 | b      |     23 |
|  5 | b      |     11 |
+----+--------+--------+

3.每个子句可以包含group by,having子句

select * from union_a where number > 50 group by t_name union select * from union_b where number< 30 group by t_name;
+----+--------+--------+
| ID | T_NAME | NUMBER |
+----+--------+--------+
|  1 | a      |    100 |
|  1 | b      |     23 |
+----+--------+--------+

4.每个子句包含limit

select * from union_a limit 2 union select * from union_b limit 1;
+----+--------+--------+
| ID | T_NAME | NUMBER |
+----+--------+--------+
|  1 | a      |    100 |
+----+--------+--------+

最后一个limit 1是对最终结果限制

select * from union_a limit 2 union (select * from union_b limit 1);
+----+--------+--------+
| ID | T_NAME | NUMBER |
+----+--------+--------+
|  1 | a      |    100 |
|  2 | a      |     28 |
|  1 | b      |     23 |
+----+--------+--------+

得到期望结果

 

以上是关于合并查询union的主要内容,如果未能解决你的问题,请参考以下文章

如何用union合并SQL查询的数据

合并查询union

mysql合并查询(多张表) union 和 union all

sql 用union合并合并查询结果

union all这样写为啥提示“使用 UNION、INTERSECT 或 EXCEPT 运算符合并的所有查询必须在其目标列表中有

SqlServer中的UNION操作符在合并数据时去重的原理以及UNION运算符查询结果默认排序的问题