2013-10-07 64 views
0

我有兩個表與我,網絡和郵件。目前我正在使用此查詢從兩個表中獲取數據。添加額外的列,同時從兩個表中選擇

PreparedStatement ps = con.prepareStatement("(select * from web where name='abc') union (select * from mail where name='abc')"); 
ResultSet rs = ps.executeQuery(); 
while(rs.next()){  
bw.write(rs3.getString("name")+"~"+rs3.getString("age")+"~"+rs3.getString("profession"); 
bw.newLine(); 
} 

輸出是這樣的。

+------+------+------------+ 
| name | age | profession | 
+------+------+------------+ 
| abc | 20 | doctor  | 
| abc | 20 | engineer | 
+------+------+------------+ 

,並在文件中的像這樣

abc~20~doctor 
abc~20~engineer 

,但我怎麼能在結果集中,這將給我的數據,這種格式

abc~20~doctor~web 
abc~20~engineer~mail 
+1

[檢查此解決方案](http://stackoverflow.com/questions/9836972/manually-add-data-to-a-java-resultset) – super

回答

0
添加一個額外的列
select * , 'web' as source from web where name='abc' union 
select *, 'mail' as source from mail where name ='abc' 
+0

非常感謝你......它的工作方式完全一樣我想... – anonymous

+0

很高興我能幫忙! –

3
try this 

select * , 'web' as tablename from web where name='abc' union 
select * ,'mail' as table namefrom mail where name='abc' 
1

試試這個

PreparedStatement ps = con.prepareStatement("(select name,age,profession ,'web' AS ExtraColumnfrom from web where name='abc') union (select name,age,profession ,'mail' AS ExtraColumnfrom mail where name='abc')"); 
ResultSet rs = ps.executeQuery(); 
while(rs.next()){  
bw.write(rs3.getString("name")+"~"+rs3.getString("age")+"~"+rs3.getString("profession")+"~"+rs3.getString("ExtraColumnfrom "); 
bw.newLine(); 
}