我有一个包含两列的数据库:
author_id, message
条目如下:
123, "message!"
123, "message!"
123, "different message"
124, "message!"
我想做一个允许我选择的查询:
123, “消息!”
或
124, “消息!”
本质上,message
相同但 author_id
不同的条目。
然后我想删除其中一个条目。 (哪一个不重要,我只能选择其中一个)。
This question让我接近,但它适用于跨两列的重复项。
最佳答案
还有一个替代示例:
-- 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)
关于ruby-on-rails - Postgres 在一列上选择重复但在另一列上选择不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44587097/