MySQL:来自两个不同列的交叉匹配记录

时间:2015-03-05 16:55:48

标签: mysql sql

我得到的表跟随者看起来像这样:

| id | follower_id | user_id |
| 1  | user1       | user2   |
| 2  | user2       | user3   |
| 3  | user2       | user1   |
| 4  | user4       | user3   |
| 5  | user3       | user2   |

当两个用户互相关注时,我需要计算实例,在这种情况下,结果应该是2,因为user1和user2,user2和user3是相互跟随的。

我尝试了LEFT JOIN,SELECT COUNT()FROM表WHERE字段IN()的各种组合,但我想我错过了一些东西......我觉得我接近这个查询的目标

SELECT
    u.id,
    u.name,
    u.img,
    ifnull((follower_id and user_id),0) as `match`
FROM table_users u
LEFT JOIN (select user_id from table_followers where follower_id = 14)   followers on u.id = followers.user_id
LEFT JOIN (select follower_id from table_followers where user_id = 14) following on u.id = following.follower_id
WHERE u.id = 14 and (follower_id or user_id)

通过此查询,我试图弄清楚user_id_14有多少关注者。

是否可以使用纯MySQL来实现这一点,或者我应该使用PHP循环解决这个问题?

这让我头疼三个小时,我找不到解决方案。

2 个答案:

答案 0 :(得分:1)

这可能对你有帮助..

Select count(*) 
From followers f1 
    joins followers f2 ON f1.follower_id = f2.user_id 
                      and f1.user_id= f2.followerid;

答案 1 :(得分:1)

SELECT
    CONVERT(COUNT(*)/2, UNSIGNED) as counter
FROM followers u
INNER JOIN (
    select 
      user_id,
      follower_id
    from followers 
) as f 
on u.user_id = f.follower_id
WHERE u.follower_id = f.user_id