我在Postgresql中遇到插入查询问题。
我有这样的查询:
select *
from (
select *,
row_number() over (partition by id order by id) as row_number
from lookup_temp
) as rows
where row_number = 1
我希望将结果插入表lookup_temp
。
我怎么能这样做?
答案 0 :(得分:1)
我假设您尝试插入lookup_temp
,其中每个id
只有一行重复 select (因为使用此select *,row_number() over (partition by id order by id) as row_numberfrom lookup_temp
)到同一张桌子lookup_temp
。如果是,下面的查询就足够了。
delete from lookup_temp where ctid in (
select ctid from (
select ctid,
row_number() over (partition by id order by id) as row_number
from lookup_temp
) as rows
where row_number <> 1)
行表格中的行版本的物理位置。注意 虽然ctid可用于非常快速地定位行版本, 如果由VACUUM FULL更新或移动,则行的ctid将会更改。 因此,ctid作为长期行标识符是无用的。 OID,或 应该使用更好的用户定义的序列号来识别 逻辑行。
答案 1 :(得分:0)
您可以从SELECT执行INSERT以将结果导入lookup_temp表
INSERT into lookup_temp (specify your columns) VALUES
(
select *
from (
select *,
row_number() over (partition by id order by id) as row_number
from lookup_temp
) as rows
where row_number = 1
)
答案 2 :(得分:0)
使用distinct on
insert into lookup_temp
select distinct on (id) *
from lookup_temp
如果要插入另一个表,请指定列
insert into another_table (id, c1, c2...)
select distinct on (id) id, c1, c2...
from lookup_temp
http://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT
答案 3 :(得分:0)
- 就这样做吧。它应该工作正常
select *
INTO lookup_temp
from (
select *, row_number() over (partition by id order by id) as row_number
from lookup_temp
) as rows
where row_number = 1