newaccount1111
newaccount1111

Reputation: 133

UNION ALL - Get Name Of Table

I am using Python with the SQLite module. 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:

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

Upvotes: 1

Views: 90

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1270401

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;

Upvotes: 3

Bernd Buffen
Bernd Buffen

Reputation: 15057

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

Upvotes: 3

Related Questions