标签:排序 括号 var 语法 comment from nio bsp arch
表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 | +----+--------+--------+
得到期望结果
标签:排序 括号 var 语法 comment from nio bsp arch
原文地址:https://www.cnblogs.com/bibiafa/p/9255021.html