0

我在另一个线程中获得了一些关于从 MySQL 中的 2 个表中提取数据的问题,看来我需要内部连接。

我的表:

USERS 
  --id (int)
  --username (varchar)

USER_FOLLOW
  -- id (int)
  -- follower (int)
  -- user (int)
  -- subscribed (current_timestamp)

查询,$following =

SELECT ufollower.id AS follower_id,
ufollower.username AS follower_name,
ufollowed.id AS user_id,
ufollowed.username AS user_name
FROM
/* JOIN twice against users, once to get the follower and once to get the followed */
user_follow 
/* users aliased as ufollower to get the follower details */
JOIN users ufollower ON ufollower.id = user_follow.follower
/* users aliased as ufollowed to get the followed details */
JOIN users ufollowed ON ufollowed.id = user_follow.user
WHERE
user_follow.user = $p_id

p_id是我正在查看的人的个人资料 ID。

我需要显示我关注的人以及我关注的人的用户名。由于某种原因,我目前拥有的代码向我展示了 3 次,而不是我关注的 3 个人:

while($apple = mysql_fetch_array($following)){
  echo '<a href="'.$apple['user_name'].'">'.htmlspecialchars($apple['user_name']).'</a> ';
}

很抱歉打开另一个线程,我已经盯着它看了好几个小时,我无法理解它。

4

3 回答 3

1

乍一看,您似乎显示了错误的用户名,显示的是关注者而不是关注者。将您的 PHP 代码更改为以下内容:

while($apple = mysql_fetch_array($following)){
  echo '<a href="'.$apple['follower_name'].'">'.htmlspecialchars($apple['follower_name']).'</a> ';
}

请注意,您的查询实际上只返回关注您的用户,它不包括您关注的用户(即带有 的用户user_follow.follower = $p_id)。当然,对于那些用户,您实际上确实想要显示该user_name列...

于 2012-10-16T01:46:47.933 回答
0
SELECT f.user,u.username,f.subscribed
FROM user_follow f inner join users u on f.user=u.id
WHERE
f.follower=1
union all
SELECT f.follower,u.username,f.subscribed
FROM user_follow f inner join users u on f.follower=u.id
WHERE
f.user=1;

The query shall retrieve person user=1 are following + person who are following user=1

于 2012-10-16T01:55:40.710 回答
-1

您正在对用户进行两次内部联接,而不是对 ufollowed 和 ufollower 进行内部联接:

SELECT ufollower.id AS follower_id,
ufollower.username AS follower_name,
ufollowed.id AS user_id,
ufollowed.username AS user_name
FROM
/* JOIN twice against users, once to get the follower and once to get the followed */
user_follow 
/* users aliased as ufollower to get the follower details */
JOIN  ufollower ON ufollower.id = user_follow.follower
/* users aliased as ufollowed to get the followed details */
JOIN ufollowed ON ufollowed.id = user_follow.user
WHERE
user_follow.user = $p_id
于 2012-10-16T01:41:43.940 回答