简体   繁体   English

UNION ALL-获取表名

[英]UNION ALL - Get Name Of Table

I am using Python with the SQLite module. 我正在将Python与SQLite模块一起使用。 I am performing a union all statement on two tables, is there a way to get the name of the table that each record came from, so when I do a fetch all it looks something like this: 我正在两个表上执行union all语句,有没有一种方法来获取每个记录来自的表的名称,所以当我执行所有操作时,它看起来像这样:

value11, value12, value13, table1
value21, value22, value23, table2
value31, value32, value33, table1

The only way I can think of doing this is by making another column in each table which contains the table name, although this would store a lot of unnecessary data if there is already something out there that will do the same. 我能想到的唯一方法是在每个包含表名称的表中另建一列,尽管如果已经有可以这样做的东西会存储很多不必要的数据。

Thanks 谢谢

You would include the table name in the query: 您将在查询中包括表名称:

select value11, value12, value13, 'table1' as which from table1
union all
select value21, value22, value23, 'table2' as which from table2
union all
select value31, value32, value33, 'table1' as which from table1;

You can use a query like this: 您可以使用如下查询:

SELECT 'table1' as tablename , t1.field1, t1.field2 FROM table1
UNION ALL
SELECT 'table2' as tablename , t2.field1, t2.field2 FROM table2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM