mysql union 和union all使用

CREATE TABLE `user_info` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COMMENT='用戶表';

INSERT INTO `test`.`user_info`(`id`, `name`, `age`) VALUES (1, 'aaa', 11);
INSERT INTO `test`.`user_info`(`id`, `name`, `age`) VALUES (2, 'bbb', 22);
INSERT INTO `test`.`user_info`(`id`, `name`, `age`) VALUES (3, 'ccc', 33);

數據以下
html

union操做mysql

select id FROM user_info WHERE age = 11 UNION SELECT id FROM user_info WHERE age = 22

結果
+----+
| id |
+----+
|  1 |
|  2 |
+----+

union allsql

mysql> select id FROM user_info WHERE age > 11 UNION ALL SELECT id FROM user_info WHERE age > 22;
+----+
| id |
+----+
|  2 |
|  3 |
|  3 |
+----+

結論:union會去除重複,union all不會去除重複的數據;code

篩選的列數不一致htm

mysql> select id,name FROM user_info WHERE age = 11 UNION ALL SELECT id FROM user_info WHERE age = 22;
報錯  
1222 - The used SELECT statements have a different number of columns

篩選列數起別名blog

mysql> select id,name name1 FROM user_info WHERE age = 11 UNION ALL SELECT id,name name2 FROM user_info WHERE age = 22;
+----+-------+
| id | name1 |
+----+-------+
|  1 | aaa   |
|  2 | bbb   |
+----+-------+
2 rows in set (0.02 sec)

結論:起別名以最開始出現的列別名爲準。文檔

數據類型不一致進行union 表中id是int的 name 是varchar類型的。get

mysql> select id FROM user_info WHERE age = 11 UNION ALL SELECT name FROM user_info WHERE age = 22;
+-----+
| id  |
+-----+
| 1   |
| bbb |
+-----+
2 rows in set (0.02 sec)

結論:不一樣數據類型的能夠合併爲1列。但業務層返回數據接收處理時可能會出問題。建議數據列最好一致。it

總結:union數據會去重,union all 數據不會去重,不一樣數據類型cloumn能夠合併爲1列。io

參考文檔

相關文章
相關標籤/搜索