我有这张桌子messages
;
sender_id recipient_id
1 2
1 3
1 3
2 1
3 1
2 3
我希望选择这样的行:
- Either
sender_id
or receiver_id
= current_user.id
.
- 其他字段应该是唯一的。
IE。我想从表中选择唯一的sender_id = 2
or recipient_id = 2
我需要这个结果:
sender_id recipient_id
2 1
2 3
怎么做?
为什么?因为我希望构建一个类似 facebook 的收件箱,其中聚合发送和接收的消息,而这个查询是迄今为止的瓶颈。
我使用的是 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
) 从结果中删除重复项DISTINCT
不必要。
您可能想添加ORDER BY
最后用于排序输出。
假设一个大表具有相对较少的合格行,则两个 Btree 索引通常可以提供最佳性能。一个带前导或仅一个sender_id
,另一个带前导或仅recipient_id
.
单个多列索引 https://www.postgresql.org/docs/current/indexes-multicolumn.html on (sender_id, receiver_id)
反之亦然也可以,但通常速度较慢。看:
- 复合索引也适合第一个字段的查询吗? https://dba.stackexchange.com/a/27493/3684
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)