简体   繁体   中英

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_from_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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM