Selecting distinct values where input is in another column

时间:2015-06-15 15:20:16

标签: mysql sql

Consider the following table:

+----+------+--------------+
| id | r_usr_id | s_usr_id |
+----+------+--------------+
| 1  | 1        |  2       |
| 2  | 2        |  1       |
| 2  | 3        |  1       |
| 2  | 3        |  2       |
| 2  | 3        |  1       |
| 2  | 3        |  2       |
+----+------+--------------+

I want to pull all unique id values where an input id is in r or s.

For example, if I pass user 1, my desired result is:

+-----+
| ids |
+-----+
| 2   |
| 3   |
+-----+

If I used user 2, the result would be:

+-----+
| ids |
+-----+
| 1   |
| 3   |
+-----+

2 个答案:

答案 0 :(得分:0)

您可以使用DISTINCT select语句和IN运算符在其中一列中搜索您的ID,如下所示:

SELECT DISTINCT id
FROM myTable
WHERE @myInput IN (rColumn, sColumn);

答案 1 :(得分:0)

根据您的示例数据,我假设您要检索r_usr_id匹配的所有s_usr_id,反之亦然?

SELECT r_usr_id FROM theTable WHERE s_usr_id = 1
UNION
SELECT s_usr_id FROM theTable WHERE r_usr_id = 1