如何检查行中的元素是否存在于其他列的某个位置而不是同一行

时间:2021-12-28 14:08:40

I have a SQL table as following

我有一个SQL表如下

--------------------------
| REPO | USER | FOLLOWER |
--------------------------
|  A   |   1  |    3     |
|  A   |   2  |    4     |
|  A   |   3  |    6     |
|  B   |   2  |    7     |
|  B   |   4  |    2     |
|  C   |   5  |    3     |
|  C   |   2  |    6     |
|  C   |   6  |    5     |
--------------------------

Now, I want to only those rows where USER follows another USER for same REPO. i.e. I want rows where elements in FOLLOWER is also in USER for same REPO.

现在,我只希望那些USER跟随另一个USER进行同一个REPO的行。即我想要行,其中FOLLOWER中的元素也在同一个REPO的USER中。

OUTPUT should be like...

输出应该像......

--------------------------
| REPO | USER | FOLLOWER |
--------------------------
|  A   |   1  |    3     |
|  B   |   4  |    2     |
|  C   |   6  |    5     |
|  C   |   2  |    6     |
--------------------------

Thank You :)

谢谢 :)

2 个解决方案

#1


0  

One simple method uses exists:

存在一种简单的方法:

select t.*
from t
where exists (select 1 from t t2 where t2.repo = t.repo and t2.follower = t.user);

#2


0  

Shouldn't the output actually be as follows, i.e. 4 rows?

输出实际上不应该如下,即4行?

--------------------------
| REPO | USER | FOLLOWER |
--------------------------
|  A   |   1  |    3     |
|  B   |   4  |    2     |
|  C   |   6  |    5     |
|  C   |   2  |    6     |
--------------------------

#1


0  

One simple method uses exists:

存在一种简单的方法:

select t.*
from t
where exists (select 1 from t t2 where t2.repo = t.repo and t2.follower = t.user);

#2


0  

Shouldn't the output actually be as follows, i.e. 4 rows?

输出实际上不应该如下,即4行?

--------------------------
| REPO | USER | FOLLOWER |
--------------------------
|  A   |   1  |    3     |
|  B   |   4  |    2     |
|  C   |   6  |    5     |
|  C   |   2  |    6     |
--------------------------