我遇到了问题(第一个问题是我很难理解SQL如何工作;)
但我有两个表,一个有user_id和user_names,而且我有一个带有“连接”的表,用户可以互相关注。
我想更改查询,以便从第二个表中获取带有连接的用户名。
这是一个SQLfiddle http://sqlfiddle.com/#!9/1779d/4
我一直在尝试这样的事情:
SELECT users_followers.user_id,
usernames.username
FROM users_followers
JOIN users usernames ON users_followers.follower_id = usernames.id
但没有运气。
所以SELECT user_id, follower_id from users_followers WHERE follower_id = 1
给了我
+---------+-------------+
| user_id | follower_id |
+---------+-------------+
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
+---------+-------------+
但我想要
+---------+-------------+
| user_id | follower_id |
+---------+-------------+
| steve | demo |
| adam | demo |
| frank | demo |
+---------+-------------+
非常感谢帮助!
答案 0 :(得分:1)
您需要将用户表加入两次
select
u1.user_name as user_name,
u2.user_name as follower_name
from users_followers uf
join users u1 on u1.user_id = uf.user_id
join users u2 on u2.user_id = uf.follower_id