SQLite Unions 子句
sqlite unions 子句
sqlite的 union 子句/运算符用于合并两个或多个 select 语句的结果,不返回任何重复的行。
为了使用 union,每个 select 被选择的列数必须是相同的,相同数目的列表达式,相同的数据类型,并确保它们有相同的顺序,但它们不必具有相同的长度。
1. 语法
union 的基本语法如下:
select column1 [, column2 ] from table1 [, table2 ] [where condition] union select column1 [, column2 ] from table1 [, table2 ] [where condition]
这里给定的条件根据需要可以是任何表达式。
假设有下面两个表,(1)company 表如下所示:
sqlite> select * from company; id name age address salary ---------- -------------------- ---------- ---------- ---------- 1 paul 32 california 20000.0 2 allen 25 texas 15000.0 3 teddy 23 norway 20000.0 4 mark 25 rich-mond 65000.0 5 david 27 texas 85000.0 6 kim 22 south-hall 45000.0 7 james 24 houston 10000.0
(2)另一个表是 department,如下所示:
id dept emp_id ---------- -------------------- ---------- 1 it billing 1 2 engineering 2 3 finance 7 4 engineering 3 5 finance 4 6 engineering 5 7 finance 6
现在,让我们使用 select 语句及 union 子句来连接两个表,如下所示:
sqlite> select emp_id, name, dept from company inner join department on company.id = department.emp_id union select emp_id, name, dept from company left outer join department on company.id = department.emp_id;
这将产生以下结果:
emp_id name dept ---------- -------------------- ---------- 1 paul it billing 2 allen engineerin 3 teddy engineerin 4 mark finance 5 david engineerin 6 kim finance 7 james finance
2. union all 子句
union all 运算符用于结合两个 select 语句的结果,包括重复行。
适用于 union 的规则同样适用于 union all 运算符。
语法
union all 的基本语法如下:
select column1 [, column2 ] from table1 [, table2 ] [where condition] union all select column1 [, column2 ] from table1 [, table2 ] [where condition]
这里给定的条件根据需要可以是任何表达式。
现在,让我们使用 select 语句及 union all 子句来连接两个表,如下所示:
sqlite> select emp_id, name, dept from company inner join department on company.id = department.emp_id union all select emp_id, name, dept from company left outer join department on company.id = department.emp_id;
这将产生以下结果:
emp_id name dept ---------- -------------------- ---------- 1 paul it billing 2 allen engineerin 3 teddy engineerin 4 mark finance 5 david engineerin 6 kim finance 7 james finance 1 paul it billing 2 allen engineerin 3 teddy engineerin 4 mark finance 5 david engineerin 6 kim finance 7 james finance