2013-05-17 45 views
6

Tôi có một trình theo dõi cơ bản/bảng sau trong mySQL giống như thế này.Bảng theo dõi kiểu theo dõi của Twitter trong SQL

id  user_id  follower_id 
1   userA  userB 
2   userC  userA 
3   userA  userC 
4   userB  userC 
5   userB  userA 

Tôi đã kiểm tra các chủ đề này nhưng couldnt tìm thấy những gì tôi cần

database design for 'followers' and 'followings'?

SQL Following and Followers

Những gì tôi cần là phải có một hệ thống như thế này:

Giả sử chúng ta đang userB (chúng tôi theo dõi userA, theo sau là userC và userA)

Tôi muốn trả lại kết quả bao gồm người theo dõi/trạng thái sau. Ví dụ cho người dùngB:

id  followedBy  areWeFollowing 
1   userA  1 
2   userC  0 

Cảm ơn sự giúp đỡ của bạn!

arda

Trả lời

2

Với truy vấn này để tìm xem bạn có theo dõi hay không, hãy theo dõi bạn.

SELECT ff1.follower_id as followedBy, 
(
    select count(follower_id) 
    from follower_following as ff2 
    where ff2.user_id = ff1.follower_id 
    and ff2.follower_id = ff1.user_id 
) as areWeFollowing 
FROM follower_following as ff1 
where user_id = 'userB'; 
+1

Có! Điều này là rất tốt cảm ơn bạn rất nhiều. PS: (Có lỗi đánh máy "như") – ardavar

+0

Cảm ơn bạn đã sửa! – ajsanchez22