SQL从具有不同列名的两个不同表中选择行

时间:2014-03-01 09:21:58

标签: java sql oracle hibernate

我想从两个不同的表(TABLE_A和TABLE_B)中选择行。我正在使用oracle db和hibernate。这是我的表格:

以下是TABLE_A

+----+--------+---------+-----------+---------------------+---------------------+
| ID | AMOUNT | BALANCE |  STATUS   |     CREATE_DATE     |      END_DATE       |
+----+--------+---------+-----------+---------------------+---------------------+
|  1 |      5 |       5 | FINISHED  | 2014-02-27 15:10:20 | 2014-02-27 15:10:20 |
|  2 |     12 |      17 | TIMED_OUT | 2014-02-27 15:10:20 | 2014-02-27 15:10:20 |
|  3 |     21 |      38 | COMMITED  | 2014-02-27 15:10:20 | 2014-02-27 15:10:20 |
+----+--------+---------+-----------+---------------------+---------------------+

以下是TABLE_B

+----+----------------+---------------+----------------+---------------------+
| ID | PAYMENT_AMOUNT | TOTAL_BALANCE | PAYMENT_STATUS |  REQUEST_TIMESTAMP  |
+----+----------------+---------------+----------------+---------------------+
|  1 |              3 |            23 | FAILED         | 2014-02-27 15:10:20 |
|  2 |             12 |            11 | FULFILLED      | 2014-02-27 15:10:20 |
|  3 |              2 |             9 | TIMED_OUT      | 2014-02-27 15:10:20 |
+----+----------------+---------------+----------------+---------------------+

我想要做的是我需要通过一个查询获得如下结果:

+--------+---------+-----------+---------------------+---------------------+
| AMOUNT | BALANCE |  STATUS   |        DATE         |      END_DATE       |
+--------+---------+-----------+---------------------+---------------------+
|      5 |       5 | FINISHED  | 2014-02-27 15:10:20 | 2014-02-27 15:10:20 |
|     12 |      17 | TIMED_OUT | 2014-02-27 15:10:20 | 2014-02-27 15:10:20 |
|     21 |      38 | COMMITED  | 2014-02-27 15:10:20 | 2014-02-27 15:10:20 |
|      3 |      23 | FAILED    | 2014-02-27 15:10:20 | null                |
|     12 |      11 | FULFILLED | 2014-02-27 15:10:20 | null                |
|      2 |       9 | TIMED_OUT | 2014-02-27 15:10:20 | null                |
+--------+---------+-----------+---------------------+---------------------+

结果为ordered by DATE。列描述如下:

AMOUNT = TABLE_A.AMOUNT or TABLE_B.PAYMENT_AMOUNT
BALANCE = TABLE_A.BALANCe or TABLE_B.TOTAL_BALANCE
STATUS = TABLE_A.STATUS or TABLE_B.PAYMENT_STATUS
DATE = TABLE_A.CREATE_DATE or TABLE_B.REQUEST_TIMESTAMP
END_DATE = TABLE_A.END_DATE or null

有没有办法在oracle db中获得那些结果,并且可以将这些结果绑定到java中的hibernate对象?

1 个答案:

答案 0 :(得分:2)

尝试这样的事情

select * from (
select id as amount, ... from t1
union all 
select id as amount, ... from t2
) t order by date