I have an SQL query which uses UNION in order to obtain data from two tables. I need a way to find out which data is coming from which table in the UI. Is there a way to insert a flag which could say about the data coming from a particular table ? I know that firing two queries may be a solution but I want to try and keep it in one query. Is there a solution ?
我有一个SQL查询,它使用UNION来从两个表中获取数据。我需要一种方法来找出哪些数据来自UI中的哪个表。有没有办法插入一个标志,可以说明来自特定表的数据?我知道解雇两个查询可能是一个解决方案,但我想尝试将其保存在一个查询中。有解决方案吗?
3 个解决方案
#1
0
You can try:
你可以试试:
SELECT 'T1' as tbl, Field1,Field2,Field3 From TABLE1 UNION
SELECT 'T2' as tbl, Field1,Field2,Field3 From TABLE2
#2
0
If you are combining data from two tables, then you should be using UNION ALL
, not UNION
. UNION
incurs overhead for removing duplicates, even if none exist.
如果要合并来自两个表的数据,那么您应该使用UNION ALL,而不是UNION。即使不存在重复项,UNION也会产生开销。
So:
所以:
select t1.*, 'table1' as which
from table1 t1
union all
select t2.*, 'table2'
from table2 t2;
The use of *
presumes that the columns and types are identical/compatible in the two tables.
使用*假定列和类型在两个表中是相同/兼容的。
#3
0
SELECT 'table1' AS 'table', * FROM table1
UNION
SELECT 'table2' AS 'table', * FROM table2
#1
0
You can try:
你可以试试:
SELECT 'T1' as tbl, Field1,Field2,Field3 From TABLE1 UNION
SELECT 'T2' as tbl, Field1,Field2,Field3 From TABLE2
#2
0
If you are combining data from two tables, then you should be using UNION ALL
, not UNION
. UNION
incurs overhead for removing duplicates, even if none exist.
如果要合并来自两个表的数据,那么您应该使用UNION ALL,而不是UNION。即使不存在重复项,UNION也会产生开销。
So:
所以:
select t1.*, 'table1' as which
from table1 t1
union all
select t2.*, 'table2'
from table2 t2;
The use of *
presumes that the columns and types are identical/compatible in the two tables.
使用*假定列和类型在两个表中是相同/兼容的。
#3
0
SELECT 'table1' AS 'table', * FROM table1
UNION
SELECT 'table2' AS 'table', * FROM table2