1. 程式人生 > >合並查詢union

合並查詢union

得到 auto HERE nbsp ble not 排序 where子句 having

表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