還有一可選示例:
-- Test table
CREATE TABLE dummy_data (
author_id int,
message text
);
-- Test data
INSERT INTO dummy_data (author_id, message)
VALUES
(123, '"message!"'),
(123, '"message!"'),
(123, '"different message"'),
(124, '"message!"'),
(124, '"message!"'),
(125, '"message!"');
-- Delete query
DELETE FROM dummy_data
WHERE ctid NOT IN (
SELECT max(ctid)
FROM dummy_data
GROUP BY message -- this is important to specify
)
-- just for test returning deleted records,
-- you may ignore it, if don't want
RETURNING *;
-- Confirming result:
SELECT * FROM dummy_data ;
author_id | message
-----------+---------------------
123 | "different message"
125 | "message!"
(2 rows)
查看更多有關係統列:https://www.postgresql.org/docs/current/static/ddl-system-columns.html
編輯:
附加例如作爲請求限制由ID的範圍(AUTHOR_ID)。
純查詢:
DELETE FROM dummy_data
USING (SELECT ARRAY[ 123, 124]) v(id)
WHERE author_id = ANY (v.id)
AND ctid NOT IN (
SELECT max(ctid)
FROM dummy_data
WHERE author_id = ANY (v.id)
GROUP BY message
);
與意見相同的查詢:
DELETE FROM dummy_data
-- Add your 'author_id' values into array here.
-- Reason we list it here with USING statement is
-- because we need to compare values in two places
-- and if list is too big it would be annoyance to
-- write it 2 times :)
USING (SELECT ARRAY[ 123, 124]) v(id)
-- First we get all the authors in the batch by ID
WHERE author_id = ANY (v.id)
-- Secondly we get max CTID to ignore using same
-- authors range in batch scope
AND ctid NOT IN (
SELECT max(ctid)
FROM dummy_data
WHERE author_id = ANY (v.id)
GROUP BY message
);
-- This will delete following rows:
author_id | message
-----------+------------
123 | "message!"
123 | "message!"
124 | "message!"
(3 rows)
-- Leaving the state to table:
author_id | message
-----------+---------------------
123 | "different message"
124 | "message!"
125 | "message!"
(3 rows)
什麼是不同的作者有多個常見消息(爲前兩者 'author_id' 123和124有 「消息2」) ?那麼什麼是可取的結果? –
@OtoShavadze同樣,只需選擇其中一個。如果同一作者有兩個副本,第二個作者有三個作品中的任何一個。 – goddamnyouryan
此表是否有主鍵? - 如果解決方案恰好選擇要刪除的'123'消息!'行,是否應該刪除所有這些行? – pozs