[英]Finding all rows with unique combination of two columns
I have this table messages
; 我有这个表messages
;
sender_id recipient_id
1 2
1 3
1 3
2 1
3 1
2 3
I wish to select rows such that: 我希望选择以下行:
sender_id
or receiver_id
= current_user.id
. sender_id
或receiver_id
= current_user.id
。 Ie I want to select unique from table where sender_id = 2
or recipient_id = 2
and I need this result: 即我想从表中选择sender_id = 2
或recipient_id = 2
唯一,我需要这个结果:
sender_id recipient_id
2 1
2 3
How to do it? 怎么做?
Why? 为什么? Because I wish to build a facebook-like inbox in which sent and received messages are aggregated, and this query is the bottleneck so far. 因为我希望建立一个类似于Facebook的收件箱,其中汇总了已发送和已接收的邮件,此查询是目前为止的瓶颈。
I am using rails 3.2 and Postgres 9.3. 我使用的是rails 3.2和Postgres 9.3。
SELECT sender_id AS user_id, recipient_id AS other_user_id
FROM messages
WHERE sender_id = $current_user_id
UNION
SELECT recipient_id, sender_id
FROM messages
WHERE recipient_id = $current_user_id
-- ORDER BY 1, 2 -- optional
UNION
(not UNION ALL
) removes duplicates from the result making DISTINCT
unnecessary. UNION
(不是UNION ALL
)从结果中删除重复项,从而不再需要DISTINCT
。 You might want to add ORDER BY
at the end for sorted output. 您可能希望在末尾添加ORDER BY
以进行排序输出。
Assuming a big table with relatively few qualifying rows, two btree indexes typically deliver best performance. 假设一个具有相对较少的限定行的大表,两个btree索引通常提供最佳性能。 One with leading or only sender_id
, another one with leading or only recipient_id
. 一个具有前导或仅具有sender_id
,另一个具有前导或仅具有recipient_id
。
A single multicolumn index on (sender_id, receiver_id)
or vice versa also works, but typically slower. (sender_id, receiver_id)
上的单个多列索引也可以,但通常较慢。 See: 看到:
With ANSI SQL: 使用ANSI SQL:
SELECT DISTINCT sender_id, reciepient_id
FROM messages
WHERE (sender_id = current_user.id or reciepient_id = current_user.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.