从不同的表中获取用户ID

时间:2013-04-20 19:58:51

标签: sql

我有一个类似Twitter的网站用于学习目的,您可以关注用户。 现在我希望获取跟踪登录人员的所有用户。

下表有三行。 id,user_id,follow_id

现在,如果用户1想要关注用户2。 行中的值为user_id = 1follow_id= 2

但是当我尝试获取具有相同follow_id的用户时,我只得到user_id 2作为回报。并非所有拥有follow_id = 2的用户

有什么想法吗?

SELECT 
    user.id, user.username, user.email,
    userdetails.profile_img, following.follow_id 
FROM 
    user 
JOIN 
    userdetails ON user.id = userdetails.user_id 
JOIN 
    following on user.id = following.follow_id 
WHERE 
    following.follow_id = 2 

这就是我的表格的样子

Following
id | user_id | follow_id

Tweets
user_id|id|date|message

user
id|email|password|username

userdetails
id|firstname|lastname|profile_img|user_id|about

任何提示?

3 个答案:

答案 0 :(得分:2)

使用JOIN following on user.id = following.follow_id更改JOIN following on user.id = following.user_id

SELECT 
    user.id, user.username, user.email,
    userdetails.profile_img, following.follow_id 
FROM 
    user 
JOIN 
    userdetails ON user.id = userdetails.user_id 
JOIN 
    following on user.id = following.user_id 
WHERE 
    following.follow_id = 2

答案 1 :(得分:1)

试试这个

SELECT * FROM Following 
INNER JOIN Users on Following.UserId=Users.Id
INNER JOIN UsersDetails on Users.Id=UserDetails.UserId
where Following.Follow_id=@UserId

当然,您可以根据需要选择列。

答案 2 :(得分:1)

SELECT user.id, user.username,user.email,
userdetails.profile_img, following.follow_id FROM user JOIN userdetails 
ON user.id = userdetails.user_id JOIN following 
ON user.id = following.follow_id WHERE following.follow_id = 2

获取与follow_id = 2:

匹配的所有用户ID
SELECT user_id from following where follow_id = 2;

(我会将下表中user_id列的名称更改为follower_id

还要从与user_id关联的userdetails表中获取数据:

SELECT userdetails.*, user.* FROM userdetails JOIN users 
ON user.id = userdetails.user_id JOIN following
ON user.id = following.***user_id*** WHERE following.follow_id = 2;

看看是否有效,我认为您的问题是您加入了以下内容。用户follow_id代替following.user_id