我有一个具有这种结构的表:
我使用此脚本查询请求:
SELECT D.DELIVERY_REQUEST_ID AS "REQUEST_ID",
'Delivery' AS "REQUEST_TYPE"
FROM DELIVERY_REQUEST D
UNION
SELECT I.INVOICE_REQUEST_ID AS "REQUEST_ID",
'Invoice' AS "REQUEST_TYPE"
FROM INVOICE_TRX I
结果如下:
REQUEST_ID | REQUEST_TYPE
__________________|____________________
|
1 | Delivery
1 | Invoice
2 | Delivery
2 | Invoice
我想要做的是在开头用一个唯一的键(应该是一个INT,就像一个自动号码)来查询(或创建一个视图),如下所示:
ID | REQUEST_ID | REQUEST_TYPE
____|________________|____________________
| |
1 | 1 | Delivery
2 | 1 | Invoice
3 | 2 | Delivery
4 | 2 | Invoice
提前谢谢。
答案 0 :(得分:5)
首先,当您添加字符串时使用UNION ALL,因此Oracle不会尝试进行不同的排序。
要实际回答问题,您可以使用分析函数ROW_NUMBER()
select row_number() over ( order by request_id, request_type ) as id
, a.*
from ( select d.delivery_request_id as request_id
, 'delivery' as request_type
from delivery_request d
union all
select i.invoice_request_id as request_id
, 'invoice' as request_type
from invoice_trx i
) a
答案 1 :(得分:1)
为什么你不尝试连续REQUEST_TYPE + REQUEST_ID
然后将其放在ID
列而不是生成ID?
ID | REQUEST_ID | REQUEST_TYPE
____|________________|____________________
| |
D1 | 1 | Delivery
I1 | 1 | Invoice
D2 | 2 | Delivery
I2 | 2 | Invoice
答案 2 :(得分:1)
你可以使用rownum:
select rownum, REQUEST_ID, REQUEST_TYPE
from
(
SELECT D.DELIVERY_REQUEST_ID AS "REQUEST_ID",
'Delivery' AS "REQUEST_TYPE"
FROM DELIVERY_REQUEST D
UNION
SELECT I.INVOICE_REQUEST_ID AS "REQUEST_ID",
'Invoice' AS "REQUEST_TYPE"
FROM INVOICE_TRX I
)
答案 3 :(得分:0)
我会说序列是最简单的方法。 如果您希望ID始终从1开始,请在查询之前重新启动序列:
ALTER SEQUENCE temp_id RESTART 1;
不知道这有多快,削减是否有更快的方法。在扩展标准SQL时,某些SQL系统也可能具有此特殊功能。