Finding all rows with unique combination of two columns

女生的网名这么多〃 提交于 2019-12-05 10:09:04
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 makingDISTINCT unnecessary. You might want to add ORDER BY at the end for sorted output.

Assuming a big table with relatively few qualifying rows, two btree indexes typically deliver best performance. One with leading or only sender_id, another one with leading or only recipient_id.

A single multicolumn index on (sender_id, receiver_id) or vice versa also works, but typically slower. See:

With ANSI SQL:

SELECT DISTINCT sender_id, reciepient_id
FROM messages
WHERE (sender_id = current_user.id or reciepient_id = current_user.id)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!