PostgreSQL刪除表中重複資料行

來源:互聯網
上載者:User

採用PostgreSQL 9.2 官方文檔例子為例:

CREATE TABLE weather (
city      varchar(80),
temp_lo  int,          -- low temperature
temp_hi  int,          -- high temperature
prcp      real,        -- precipitation
date      date
);

INSERT INTO weather VALUES
('San Francisco', 46, 50, 0.25, '1994-11-27'),
('San Francisco', 43, 57, 0, '1994-11-29'),
('Hayward', 37, 54, NULL, '1994-11-29'),
('Hayward', 37, 54, NULL, '1994-11-29');  --- duplicated row

這裡有3中方法:

第一種:替換法

-- 剔除重複行的資料轉存到新表weather_temp
SELECT DISTINCT city, temp_lo, temp_hi, prcp, date
INTO weather_temp
FROM weather;
-- 刪除原表
DROP TABLE weather;
-- 將新表重新命名為weather
ALTER TABLE weather_temp RENAME TO weather;

或者

-- 建立與weather一樣的表weather_temp
CREATE TABLE weather_temp (LIKE weather INCLUDING CONSTRAINTS);
-- 用剔除重複行的資料填充到weather_temp中
INSERT INTO weather_temp SELECT DISTINCT * FROM weather;
-- 刪除原表
DROP TABLE weather;
-- 將新重新命名為weather.
ALTER TABLE weather_temp RENAME TO weather;

通俗易懂,有很多毀滅性的操作如DROP,而且當資料量大時,耗時耗空間。不推薦。

第二種: 添加欄位法

-- 添加一個新欄位,類型為serial
ALTER TABLE weather ADD COLUMN id SERIAL;
-- 重複資料刪除行
DELETE FROM weather WHERE id
NOT IN (
SELECT max(id)
FROM weather
GROUP BY city, temp_lo, temp_hi, prcp, date
);
-- 刪除添加的欄位
ALTER TABLE weather DROP COLUMN id;

需要添加欄位,「暫時不知道Postgres是如何處理添加欄位的,是直接在原表追加呢,還是複製原表組成新表呢?」,如果是原表追加,可能就會因為新欄位的加入而導致分頁(一般block: 8k),如果是複製的話那就罪過了。不好。

第三種:系統欄位[查看 System Columns]

DELETE FROM weather
WHERE ctid
NOT IN (
SELECT max(ctid)
FROM weather
GROUP BY city, temp_lo, temp_hi, prcp, date
);

針對性強[Postgres專屬],但是簡單。

PostgreSQL 的詳細介紹:請點這裡
PostgreSQL 的:請點這裡

推薦閱讀:

在PostgreSQL中如何重複資料刪除記錄

Ubuntu下LAPP(Linux+Apache+PostgreSQL+PHP)環境的配置與安裝

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.