0

我正在构建一个用户可以关注其他用户并被关注的应用程序。

用户还可以查看另一个用户正在关注谁。

现在假设user1正在查看user2关注的人,我需要找到 user2 关注的所有人员 ID,并将其与 user1 关注的人进行比较。

而不是只返回与 user1 和 user2 匹配的所有用户的 ID(我在其他论坛中看到过),我需要检索所有 user2 的以下 ID 和用户名以及一个指示被关注人是否是的标志紧随其后的是 user1。

我已经让它在 PHP 中工作,每个查询都有一个双 for 循环,但我担心这段代码会很昂贵,并且使用单个 MYSQL 查询会更好地优化。

相关表和列:

following_table
  follower_id
  followed_id
  following: varchar -- 'true' or 'false'

user_table
  user_id
  user_name

这是我的PHP代码:

$user_id1 = '1991';
$myFollowingQuery = "SELECT following_table.followed_id, user_table.user_name
                     FROM following_table 
                     INNER JOIN user_table ON
                     following_table.followed_id = user_table.user_id
                     WHERE following_table.following = 'true'
                     AND following_table.follower_id = '$user_id1'";

$user_id2 = '1985';
$userFollowingQuery = "SELECT following_table.followed_id, user_table.user_name
                       FROM following_table 
                       INNER JOIN user_table ON
                          following_table.followed_id = user_table.user_id
                       WHERE following_table.following = 'true'
                       AND following_table.follower_id = '$user_id2'";

$userFollowingResult = mysql_query($userFollowingQuery) 
                             or doResponse('error',"Couldn't connect to the database");
$myFollowingResult = mysql_query($myFollowingQuery) 
                             or doResponse('error',"Couldn't connect to the database");

            for($i = 0; $i< mysql_num_rows($userFollowingResult);$i++){

$loopArray = array(followed_id => mysql_result($userFollowingResult,$i,"followed_id"),
                   followed_name => mysql_result($userFollowingResult,$i,"user_name"));

for($j = 0; $j< mysql_num_rows($myFollowingResult);$j++){
  if(mysql_result($userFollowingResult,$i,"followed_id")
     ==mysql_result($myFollowingResult,$j,"followed_id")) {
     $loopArray['is_following'] = 'true';
     break;
  }
  if($j==mysql_num_rows($myFollowingResult)-1){
    $loopArray['is_following'] = 'false';
    break;
  }
}

$resultArray[$i] = $loopArray;
}

echo json_encode($resultArray);
4

1 回答 1

1

这是一个简化的查询:

http://sqlfiddle.com/#!2/6b8d6/3

SELECT
  user.user_id,
  user.user_name,
  he.follower_id AS follower_id,
  IF(me.followed_id,1,0) AS metoo

FROM       following AS he

INNER JOIN user
   ON user.user_id = he.followed_id

LEFT  JOIN following AS me
   ON me.follower_id = 1
  AND me.followed_id = he.followed_id

WHERE he.follower_id = 2
于 2012-07-06T04:27:46.263 回答