2010-05-14 68 views
1

我有兩個相同的表。 我需要工會它們這樣的方式:UNION中的SELECT表名

SELECT f1,f2, xxx 
FROM 
(SELECT  * 
FROM   tbl1 
UNION ALL 
SELECT  * 
FROM   tbl2) 

其中xxx將查詢表名,其中f1和f2字段取自。 示例輸出:

123 345 'tbl1' -- this rows are from the first table 
121 345 'tbl1' 
121 345 'tbl1' 
123 345 'tbl1' 
124 345 'tbl1' 
125 345 'tbl2' -- this rows are from the second table 
127 345 'tbl2' 

在此先感謝您。

回答

2
SELECT f1,f2, xxx 
FROM 
(SELECT  *, 'tbl1' as xxx 
FROM   tbl1 
UNION ALL 
SELECT  *, 'tbl2' as xxx 
FROM   tbl2)