我正在创建一个表并使用query1 union query2将数据插入该表。问题是我想将row_number()添加到表中,但是当我将row_number()over()添加到任一查询时,编号仅适用于query1或query2,但不适用于整个表。
我做了一个hack来获取我的结果,我使用insert query1 union query2将数据插入表(table_no_serial),然后我创建了第二个表,就像这样
insert into table_w_serial select row_number() over(), * from table_no_serial;
第一次有可能做到这一点吗?
insert into table purchase_table
select row_number() over(), w.ts, w.tail, w.event, w.action, w.msg, w.tags
from table1 w
where
w.action = 'stop'
union
select row_number() over(), t.ts, t.tail, t.event, t.action, t.msg, t.tags
from table2 t
where
f.action = 'stop';
我想要这样的东西工作。
我想编写一个代码,其中结果表(endtable)将是第一个查询和第二个查询的并集,并且将在两个查询中包含一个常量行号,这样如果query1返回50个结果,query2返回40个结果。结束表的行号为1-90
使用子查询:
insert into table purchase_table ( . . . ) -- include column names here
select row_number() over (), ts, tail, event, action, msg, tags
from ((select w.ts, w.tail, w.event, w.action, w.msg, w.tags
from table1 w
where w.action = 'stop'
) union all
(select w.ts, w.tail, w.event, w.action, w.msg, w.tags
from table2 w
where f.action = 'stop'
)
) w;
请注意,这也将union
更改为union all
。 union all
效率更高;如果你想要消除重复的开销,只使用union
。