开发者

SQL Query To Select Distinct Value

I've got a table tbl_mail with the following structure:

tbl_mail
____________
mail_from_user_id
mail_to_user_id

I want to find all people with whom I once had a conversation. I could write to them or the could write to me, and I need to know the id number of the opponent. Let's say I've got id number 1.

tbl_mail
___________
mail_fro开发者_Python百科m_user_id | mail_to_user_id
------------------------------------
1                 | 2
1                 | 3
4                 | 1

In the example above I wrote to 2 different people (id`s - 2 & 3), and another person wrote to me ( number 4 ). How can I find out all people I interacted with (except for myself).


Use:

SELECT a.mail_from_user_id AS user
  FROM TBL_MAIL a
 WHERE a.mail_to_user_id = 1
UNION 
SELECT b.mail_to_user_id AS user
  FROM TBL_MAIL b
 WHERE b.mail_from_user_id = 1

UNION will remove duplicates. UNION ALL would not, and be faster for it.


select mail_to_user_id as mailid from tbl_mail where mail_from_user_id=1
     union 
    select mail_from_user_id as mailid from tbl_mail where mail_to_user_id=1

Where 1 is your id. Replace it with desired id.


Quick hack:

Select idx from (Select mail_from_user_id as idx from tbl_mail where mail_to_user_id = 1 group by mail_from_user_id Union Select mail_to_user_id as idx from tbl_mail where mail_from_user_id = 1 group by mail_to_user_id) group by idx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜