SQLite UNION ALL 运算符
SQLite 中的 UNION ALL
运算符用于结合两个 SELECT 语句的结果,包括重复行
UNION ALL
类似于 UNION,不同的是它可以有重复的行
语法
UNION ALL
的语法规则如下
SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] UNION ALL SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition]
为了使用 UNION ALL
,每个 SELECT 被选择的列数必须是相同的,相同数目的列表达式,相同的数据类型,并确保它们有相同的顺序,但它们不必具有相同的长度
范例
先运行下面的 SQL 语句创建测试数据
DROP TABLE IF EXISTS `tbl_language`; DROP TABLE IF EXISTS `tbl_rank`; CREATE TABLE IF NOT EXISTS `tbl_language`( `id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(64) NOT NULL, `url` VARCHAR(128) NOT NULL, `founded_at` DATE, PRIMARY KEY ( `id` ) ); CREATE TABLE IF NOT EXISTS `tbl_rank`( `id` INT UNSIGNED AUTO_INCREMENT, `name` VARCHAR(64) NOT NULL, `month` VARCHAR(7) NOT NULL, `rank` TINYINT NOT NULL, `rate` VARCHAR(32) NOT NULL, PRIMARY KEY ( `id` ) ); INSERT INTO `tbl_language` VALUES (1,'Python','https://www.twle.cn','1991-2-20'), (2,'PHP','http://www.php.net','1994-1-1'), (3,'Ruby','https://www.ruby-lang.org/','1996-12-25'); INSERT INTO `tbl_rank` VALUES (1, 'Python','2018-04',4,'5.083%'), (2, 'PHP','2018-04',6,'4.218%'), (3, 'Ruby','2018-04',11,'2.018%'), (4, 'Java','2018-04',1,'15.777%'), (5, 'Python','2018-03',4,'5.869%'), (6, 'PHP','2018-03',7,'4.010%'), (7, 'Ruby','2018-03',12,'2.744%'), (8, 'Java','2018-03',1,'14.941'), (9, 'Python','2018-02',4,'5.168%'), (10, 'PHP','2018-02',7,'3.420%'), (11, 'Ruby','2018-02',10,'2.534%'), (12, 'Java','2018-02',1,'14.988%');
tbl_language
表中的数据如下
+----+--------+----------------------------+------------+ | id | name | url | founded_at | +----+--------+----------------------------+------------+ | 1 | Python | https://www.twle.cn | 1991-02-20 | | 2 | PHP | http://www.php.net | 1994-01-01 | | 3 | Ruby | https://www.ruby-lang.org/ | 1996-12-25 | +----+--------+----------------------------+------------+
tbl_rank
表中的数据如下
+----+--------+---------+------+---------+ | id | name | month | rank | rate | +----+--------+---------+------+---------+ | 1 | Python | 2018-04 | 4 | 5.083% | | 2 | PHP | 2018-04 | 6 | 4.218% | | 3 | Ruby | 2018-04 | 11 | 2.018% | | 4 | Java | 2018-04 | 1 | 15.777% | | 5 | Python | 2018-03 | 4 | 5.869% | | 6 | PHP | 2018-03 | 7 | 4.010% | | 7 | Ruby | 2018-03 | 12 | 2.744% | | 8 | Java | 2018-03 | 1 | 14.941 | | 9 | Python | 2018-02 | 4 | 5.168% | | 10 | PHP | 2018-02 | 7 | 3.420% | | 11 | Ruby | 2018-02 | 10 | 2.534% | | 12 | Java | 2018-02 | 1 | 14.988% | +----+--------+---------+------+---------+
下面的 SQL 语句从 tbl_language
和 tbl_rank
表中选取所有的 name(可能有重复的值)
SELECT name FROM tbl_language UNION ALL SELECT name FROM tbl_rank ORDER BY name;
执行以上 SQL 输出结果如下
name ---------- Java Java Java PHP PHP PHP PHP Python Python Python Python Ruby Ruby Ruby Ruby