Sql 从postgres数据库中删除重复条目
我在尝试从数据库中删除多个非常相似但不完全相同的条目时遇到了一些问题。我在这里看到了许多其他解决方案: 每次我尝试从表中删除多个重复项时,该命令都会删除所有条目,而不仅仅是删除重复项 这是一个重复样本的表格,我们应该只保留一个唯一的hdrtime:Sql 从postgres数据库中删除重复条目,sql,postgresql,Sql,Postgresql,我在尝试从数据库中删除多个非常相似但不完全相同的条目时遇到了一些问题。我在这里看到了许多其他解决方案: 每次我尝试从表中删除多个重复项时,该命令都会删除所有条目,而不仅仅是删除重复项 这是一个重复样本的表格,我们应该只保留一个唯一的hdrtime: SELECT * from stdtextproducts where xxxid='DEN' AND nnnid='MTR' and hdrtime='270600'; cccid | datacrc | hdrtime | nnnid |
SELECT * from stdtextproducts where xxxid='DEN' AND nnnid='MTR' and hdrtime='270600';
cccid | datacrc | hdrtime | nnnid | site | wmoid | xxxid | bbbid | inserttime | product | reftime
-------+------------+---------+-------+------+--------+-------+-------+-------------------------+--------------------------------------------------------------------------+---------------
DEN | 3680361181 | 270600 | MTR | KDEN | SAUS70 | DEN | RRF | 2018-08-27 05:55:51.811 | SAUS70 KDEN 270600 RRF +| 1535349351811
| | | | | | | | | METAR KDEN 270553Z 22017KT 10SM BKN150 OVC200 23/06 A2991 RMK AO2 PK WND+|
| | | | | | | | | 22026/0456 SLP028 T02330056 10289 20222 58004 |
DEN | 1538417601 | 270600 | MTR | KDEN | SAUS70 | DEN | RRM | 2018-08-27 05:57:57.356 | SAUS70 KDEN 270600 RRM +| 1535349477356
| | | | | | | | | METAR KDEN 270553Z 22017KT 10SM BKN150 OVC200 23/06 A2991 RMK AO2 PK WND+|
| | | | | | | | | 22026/0456 SLP028 T02330056 10289 20222 58004 |
(2 rows)
我尝试了以下方法:
DELETE FROM stdtextproducts a USING (SELECT MIN(ctid) as ctid, hdrtime FROM stdtextproducts GROUP BY hdrtime HAVING COUNT(*) > 1) b WHERE a.hdrtime = b.hdrtime AND a.ctid <> b.ctid;
DELETE FROM stdtextproducts WHERE reftime NOT IN (SELECT MAX(reftime) FROM stdtextproducts GROUP BY hdrtime);
我应该只期待一个条目出现在列表上,但似乎所有条目都不存在了
SELECT * from stdtextproducts where xxxid='DEN' AND nnnid='MTR' and hdrtime='270600';
cccid | datacrc | hdrtime | nnnid | site | wmoid | xxxid | bbbid | inserttime | product | reftime
-------+---------+---------+-------+------+-------+-------+-------+------------+---------+---------
(0 rows)
我错过了什么
提前谢谢。试试下面的方法
DELETE FROM stdtextproducts a where
a.ctid<>
(SELECT MIN(b.ctid) as ctid
FROM stdtextproducts b
where a.hdrtime=b.hdrtime
)
或
如果此选项不起作用,您确定除了hrdtime之外,这里没有其他键吗?我尝试了第一个选项,但时间太长了。第二个选项删除表中的所有内容。Oh和T1.DEN应该是T1.xxxid列。@RayY对于第二个选项,您需要键连接,是的,第一个太慢了,因为它正在工作,对于其他正在从google寻找解决方案的人,我对您的第二种方法进行了一些调整,并提出了以下有效方法:使用stdtextproducts b从stdtextproducts a中删除,其中a.ctid
DELETE FROM stdtextproducts T1
USING stdtextproducts T2
WHERE T1.ctid < T2.ctid -- delete the older versions
AND T1.hdrtime= T2.hdrtime ; -- add more columns if needed
DELETE FROM stdtextproducts a where
exists
(SELECT *
FROM stdtextproducts b
where a.hdrtime=b.hdrtime
and b.ctid<a.ctid
)