2

「followed」はフォローされているユーザーのID、「follower」は次のことを行ったユーザーのIDである「friends」というテーブルがあります。次のように設定します。

id  |  followed  |  follower
------------------------------
1   |     34     |    67
2   |     89     |    65
3   |     67     |    34
4   |     51     |    12
5   |     78     |    18
6   |     18     |    78

ユーザーが誰をフォローしているかを表示するクエリと、誰がユーザーをフォローしているかについてのクエリを簡単に実行できますが、私ができるようにしたいのは、友情がどこで往復しているかを示す単一のクエリを実行することです。

SELETCT * FROM friends WHERE
 -- follower and followed have followed each other

したがって、上記の場合、これは ID 1 と 5 (または 3 と 6) を返します。

単一のクエリでこのマッチングを実現するにはどうすればよいですか?

4

4 に答える 4

3
Select f1.id, f2.id FROM friends as f1
JOIN friends as f2
ON f1.followed = f2.follower AND f1.follower = f2.followed 
于 2013-09-11T11:27:39.187 に答える
1

このフィドルをチェックしてください

次の条件で join を使用するだけです

 select * from 
 temp t1 join temp t2 
     where t1.follower=t2.followed 
     and t1.followed=t2.follower
于 2013-09-11T11:30:54.330 に答える
0

もちろん、これは可能です。SQL は非常に強力です。exists以下は、相関サブクエリを持つ句を使用して実行する例です。

select f.*
from follows f
where exists (select 1
              from follows f2
              where f2.followed = f.follower and f2.follower = f.followed
             );
于 2013-09-11T11:26:32.657 に答える
0

以下を使用またはクエリできます

SELECT *
FROM `friends`
WHERE (
`follower` = '34'
OR followed = '34'
)
于 2013-09-11T11:29:08.960 に答える