[英]Vertically concatenate columns from different tables in SQLite
I've got several tables, which share the same columns.我有几个表,它们共享相同的列。 I need to create a query/view where I vertically concatenate these columns.我需要创建一个查询/视图,在其中垂直连接这些列。 In addition, I need a second column that holds the name of the table where the particular value is coming from.此外,我需要第二列来保存特定值来自的表的名称。
Here's my toy schema:这是我的玩具模式:
CREATE TABLE table_1 (ID INTEGER);
CREATE TABLE table_2 (ID INTEGER);
Let's assume the tables hold the following values:让我们假设这些表包含以下值:
table_1
ID
1
2
3
table_2
ID
4
5
2
My result should look like this:我的结果应该是这样的:
table_result
ID SourceTable
1 table_1
2 table_1
3 table_1
4 table_2
5 table_2
2 table_2
SELECT ID, 'table_1' AS SourceTable FROM table_1
UNION ALL
SELECT ID, 'table_2' AS SourceTable FROM table_2
Note, this is preferred to just using UNION
as that also removes duplicates.请注意,这比仅使用UNION
更可取,因为它也可以删除重复项。 UNION ALL
doesn't expend any resources trying to de-duplicate anything. UNION ALL
不会花费任何资源来尝试删除任何内容。
Use union all
:使用union all
:
select id, 'table_1' as sourcetable
from table_1
union all
select id, 'table_2' as sourcetable
from table_2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.